使用连接将相关子查询转换为NOT EXIST和MINUS

时间:2015-03-18 16:20:28

标签: sql oracle oracle10g

我被要求使用NOT EXIST和MINUS将以下相关子查询转换为没有NOT EXISTS运算符的查询。

架构非常简单:

Student(Stud_no: Varchar, Stud_name: Varchar, Dept: Varchar)
Membership(Mem_no: Number, Stud_no: Varchar, Fine: Number)
Book(book_no: Number, book_name: Varchar, author: Varchar, Category: Varchar)
Iss_rec(iss_no: Number, iss_date: date, Mem_no: Number, book_no: Number)

要查找已借用所有图书的学生的Mem_no,我的查询是,

SELECT MEM_NO FROM MEMBERSHIP A WHERE NOT EXISTS ((SELECT BOOK_NO FROM BOOK) MINUS (SELECT BOOK_NO FROM ISS_REC B WHERE A.MEM_NO = B.MEM_NO));

现在,当我尝试使用连接实现它时,我收到错误。

SELECT A.MEM_NO FROM MEMBERSHIP A LEFT OUTER JOIN ((SELECT BOOK_NO FROM BOOK) MINUS (SELECT BOOK_NO FROM ISS_REC B WHERE A.MEM_NO = B.MEM_NO)) C ON A.MEM_NO = C.BOOK_NO WHERE C.BOOK_NO IS NULL;

任何人都可以帮助我......

1 个答案:

答案 0 :(得分:1)

此查询应该按预期工作:它将为您提供借阅Book表中所有书籍的学生列表。它不包含NOT EXIST或MINUS(我猜这个限制仅用于学术目的)。看到它使用http://sqlfiddle.com/#!4/19e78/2

处的相同数据
 select m.stud_no, count(distinct i.book_no) from membership m join    iss_rec i 
 on i.mem_no=m.mem_no
group by m.stud_no
 having count(distinct i.book_no)=(select count(*) from book)

请注意,此解决方案假定存在参照完整性(例如,在iss_rec中不存在book_no,这不在book表中)