日期:2014-05-17  浏览次数:20849 次

一个涉及到多个表的查询
现在数据库有三个表:
UserInfo(用户信息表),字段如下:
UserID   --用户ID
UserName   --用户名

BookPreBorrowInfo(图书预借信息表),字段如下:
ID  
UserID   --预借人的ID,作为用户信息表UserID外键
BooKID   --所预借的图书ID


MagaPreBorrowInfo(杂志预借信息表),字段如下:
ID
UserID   --预借人的ID,作为用户信息表UserID外键
MagaID   --所预借的杂志ID

现在我要查询所有有预借行为用户名(无论是借图书还是借杂志),还要求唯一(就是比如甲既借了图书又借了杂志那么查询结果只能出现甲一次)。

我写了一个查询语句:
select   unique   t1.userName   from   UserInfo   t1,BookPreBorrowInfo   t2,MagaPreBorrowInfo   t3   where   t1.UserID   in   t2.UserID   and   t1.UserID   in   t3.UserID

但是不对。我想那个查询条件不应是and,而应是or。不知是不是这样?



------解决方案--------------------
這個問題好像在哪見過.
select
decode(nvl(t.UserID,0),0,v.UserID,t.UserID) userID,
t.BookID,
v.MagaID
from bookPreBorrowInfo t
full join magaPreBorrowInfo v on t.UserID=v.UserID
------解决方案--------------------
用左连接不行吗?然后再判断 BooKID 和 MagaID 是否为空就可以了

难道我理解有误?