我想获取有2位作者的书的详细信息,为此,我写了以下查询。
SELECT BOOK.Book_Title
, PUBLISHER.Publisher_Name
, BOOK.Book_Type
, AUTHOR.Author_Last
, AUTHOR.Author_First
FROM AUTHOR
, WROTE
, BOOK
, PUBLISHER
WHERE AUTHOR.Author_Num = WROTE.Author_Num
AND WROTE.Book_Code = BOOK.Book_Code
AND BOOK.Publisher_Code = PUBLISHER.Publisher_Code
HAVING COUNT(WROTE.Book_Code) = 2;
但是当我运行它时,我得到了0行返回。尽管表格中有可用的数据,但有几行,其中有2位作者反对一本书。
这是我要在其中应用查询的架构。
以下是WROTE表中可用的数据,它是BOOK和AUTHOR表的多对多关系。
请告诉我问题出在哪里?
答案 0 :(得分:0)
您的查询不正确,因为在尝试应用假设具有某些分组字段的HAVING条件时,它没有GROUP BY部分。
我想使用以下查询(MS SQL):
SELECT bk.Book_Title
, pb.Publisher_Name
, bk.Book_Type
, auth.Author_Last
, auth.Author_First
FROM AUTHOR as auth
join WROTE as wr on auth.Author_Num = wr.Author_Num
join BOOK as bk on wr.Book_Code = bk.Book_Code
join PUBLISHER as pb on bk.Publisher_Code = pb.Publisher_Code
where exists (SELECT 1
from WROTE as wr_ex
where wr_ex.Book_Code = wr.Book_Code
group by wr_ex.Book_Code
having count(1) = 2 )
可能有一个子查询的变体,该子查询在FROM部分中选择有2位作者的Book_codes,应该通过加入所有其他内容来关注