我正在尝试创建一个查询,其中我可以查看第1类和第2类中的所有书籍(例如恐怖和小说),但也会显示该书所属的类别。我该怎么做?我只能假设我需要一个递归子查询,但这可能效率低下。
SELECT book.bookid,
book.author,
book.title,
Group_concat(DISTINCT category.categorydesc)
FROM book,
bookscategories,
category
WHERE book.bookid = bookscategories.bookid
AND bookscategories.categoryid = category.categoryid
AND category.categoryid = 1
AND category.categoryid = 2
GROUP BY book.bookid;
答案 0 :(得分:1)
select b.bookid, b.author, b.title, group_concat(distinct c.categorydesc)
from book as b
inner join bookcategories as bc on b.bookid = bc.bookid
inner join categories as c on bc.categoryid = c.categoryid
where b.bookid in (select bc1.bookid
from bookcategories as bc1
inner join bookcategories as bc2 on bc1.bookid = bc2.bookid
where bc1.categoryid = 1 and bc2.categoryid = 2)
group by b.bookid;
我不确定此查询的性能,因为它使用了bookcategories表3次。
选择b.author和b.title在技术上并不正确,但在这种情况下应该有效,因为b.bookid可能是唯一的。否则,不可能选择既不是group by子句的一部分也不能在聚合函数中使用的东西。
我相信您发布的代码将始终返回空结果集,因为您将category.categoryid限制为同时为1和2。