开发者

Subquery to show all other categories one to many relationships

I am trying to create a query where I can view all the books that are in both category 1 and 2 (e.g. horror and fiction) but also show the categories that the book also belongs to. How do I go about this? I can only assume that I'm going to need a recursive subquery, however this could be inefficient.

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
       A开发者_如何学编程ND category.categoryid = 2
GROUP  BY book.bookid;


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;

I am not sure about the performance of this query because it uses the bookcategories table 3 times.

Selecting b.author and b.title is not technically correct, but should work in this case because b.bookid is probably unique. Otherwise it is not possible to select something that is neither part of the group by clause nor used in an aggregate function.

I believe that the code that you posted will always return an empty result set because you are restricting category.categoryid to be both 1 and 2 at the same time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜