【问题标题】:How can i list authors with their book count, including those who have 0 books?我如何列出作者的书数,包括那些有 0 本书的作者?
【发布时间】:2019-03-26 23:23:54
【问题描述】:

我有一些任务,帮助我练习 SQL,但遇到了一些麻烦

我的数据库中有 2 个表 -> authors(authorId, Name) 和 books(bookId, authorId, title)。

所以我的任务的第一部分是把作者和他们的书数放在一起,所以我这样做了:

SELECT authors.name, COUNT(*) AS 'number of books' FROM authors, books WHERE authors.authorId=books.authorId GROUP BY authors.name;

现在我需要显示作者的书籍数量,包括书籍数量为零的作者,我该怎么做?

谢谢!

【问题讨论】:

    标签: sql


    【解决方案1】:

    你必须使用Left join

    SELECT authors.name, sum(case when bookId is null then 0 else 1 end) AS 'number of books' FROM authors
    left join books on authors.authorId=books.authorId 
    GROUP BY authors.name;
    

    【讨论】:

    • 当我这样做时发生了奇怪的事情 - 它列出了所有 7 位作者并说他们每个人都有 1 本书,即使 ID 为 3 的作者根本没有书。
    猜你喜欢
    • 2013-10-19
    • 2013-03-30
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多