我不知道我是否正确表达了我的问题,但是我是SQL的新手,我真的不知道如何措辞。我正在查询有关作者及其所写书籍的信息,我想甚至包括那些有0本书的人。我该怎么做。这是我的代码,可以正常工作,但是遗漏了0本书:
SELECT surname as "Surname", forename as "Forename", COUNT(*) as "Books written"
FROM book
LEFT OUTER JOIN author ON author.authorid = book.authorid
GROUP BY surname, forename
ORDER BY surname;
答案 0 :(得分:4)
您从错误的级别开始。如果您希望所有作者都从作者开始。但是,由于您是从书本开始的,所以说给我所有符合我的标准的书,然后再加入作者。
SELECT surname as "Surname"
, forename as "Forename"
, COUNT(book.authorid) as "Books written"
FROM author
LEFT OUTER JOIN book ON author.authorid = book.authorid
GROUP BY surname, forename
ORDER BY surname;
答案 1 :(得分:1)
您应该反转选择的x联接,从作者中选择,然后联接其书籍。另外,您必须更改book.authorid属性的计数,因为这是您要计数的。
SELECT surname as "Surname", forename as "Forename", COUNT(book.authorid) as "Books written"
FROM author
LEFT OUTER JOIN book ON author.authorid = book.authorid
GROUP BY surname, forename
ORDER BY surname;
这里的概念是,您要获取数据库中的所有作者,然后将其加入书中(甚至返回自从LEFT JOIN之后没有任何书的作者),而不是选择书,然后加入数据库作者。
从DevMedia拍摄的图片
答案 2 :(得分:0)
在count()
内而不是count(*)
内使用列名:
SELECT a.surname as "Surname", a.forename as "Forename", COUNT(b.authorid) as "Books written"
FROM book b LEFT OUTER JOIN
author a
ON a.authorid = b.authorid
GROUP BY a.surname, a.forename
ORDER BY a.surname;