使用子查询加入

时间:2015-04-09 04:12:32

标签: sql oracle subquery

我有两个名为“Book”和“Author”的表。 “Book”表的属性为: PK-Book_Num,Book_Title,Book_Year,Book_Cost,Book_Subject。“作者”表的属性为 PK-Au_ID,Au_Fname,Au_Lname。< / strong>这两个表之间具有M:N关系,它们之间的桥表名为“Writes”,它有两个表中的复合主键,由 Book_Num和Au_ID组成。这是我的问题:我想编写一个查询来显示所有从未写过主题为“编程”的书的作者的Au_ID,Au_Fname,Au_Lname,并按Au_Lname排序结果。我将如何使用子查询来执行此操作?

2 个答案:

答案 0 :(得分:0)

试一试:

SELECT A.Au_ID, A.Au_Fname, A.Au_Lname FROM Author A 
  JOIN Writes W ON A.Au_ID = W.Au_ID
  JOIN Book B ON B.Book_Num = W.Book_Num
  WHERE A.Au_ID NOT IN (
    SELECT A.Au_ID FROM Author A 
      JOIN Writes W ON A.Au_ID = W.Au_ID
      JOIN Book B ON B.Book_Num = W.Book_Num
      WHERE B.Book_Subject = 'Programming'
  )
  ORDER BY A.Au_Lname ASC;

答案 1 :(得分:0)

如果您想获得更好的性能,可以使用“NOT EXISTS”来获取所需的数据。

SELECT Au_ID, Au_Fname, Au_Lname FROM Author
WHERE NOT EXISTS 
(
    SELECT A.Au_ID FROM Author A 
    JOIN Writes W ON A.Au_ID = W.Au_ID
    JOIN Book B ON B.Book_Num = W.Book_Num
    WHERE B.Book_Subject = 'Programming'
    AND Author.Au_ID = A.Au_ID 
)
ORDER BY Au_Lname ASC