如何在多对多场景中查询没有作者的书籍

时间:2015-05-04 20:42:36

标签: mysql many-to-many

我在相关书籍和作者方面有以下数据库设计:

图书(BOOKID,标题) 作者(AUTHORID,AUTHORNAME) BooksAuthors(BOOKID,AUTHORID)

我与作者查询记录没有问题,但我无法提取没有作者的记录。我的基础是假设有没有作者的书。 顺便说一句,这是我的查询:

SELECT DISTINCT Books.title, 
                GROUP_CONCAT(DISTINCT Authors.authorname SEPARATOR ', ') AS authors 
FROM Books 
INNER JOIN BooksAuthors USING (bookid) 
INNER JOIN Authors USING (authorid) GROUP BY  books.bookid

2 个答案:

答案 0 :(得分:0)

SELECT bookid, title FROM Books INNER JOIN (
    SELECT bookid FROM BooksAuthors WHERE authorid IS NULL) AS T1
ON Books.bookid = T1.bookid;

这基本上可以解决问题。

答案 1 :(得分:0)

尝试使用LEFT JOIN,也许您需要额外添加 HAVING 部分...尝试不用和使用,看看你得到了什么

SELECT DISTINCT Books.title, 
            GROUP_CONCAT(DISTINCT Authors.authorname SEPARATOR ', ') AS authors 
FROM Books 
INNER JOIN BooksAuthors ON BooksAuthors.bookid = Books.bookid
LEFT JOIN Authors ON Authors.authorid = BooksAuthors.authorid
GROUP BY books.bookid
HAVING Authors.authorid IS NOT NULL