尝试解决这个问题很麻烦
写一个查询以显示写书的作者人数
作者(作者ID,作者姓名,地址,电话号码,发布者代码)
图书(图书ID,名称,发行日期,价格,作者ID)
我有
SELECT a.AuthorName, COUNT(b.*) AS ‘number of books written’
FROM Author a JOIN Book b ON a.AuthorID = b.BookID
GROUP BY a.AuthorName;
计算每个作者写的书数。
我知道这不是正确的,但我无法弄清楚??
答案 0 :(得分:1)
您非常接近。您需要加入作者ID。您目前正在混合作者和书籍ID,这可能不正确。
SELECT
a.AuthorName,
COUNT(b.*) AS ‘number of books written’
FROM Author a
JOIN Book b ON a.AuthorID = b.AuthorID
GROUP BY a.AuthorName;
答案 1 :(得分:1)
如果您只想获得一个数字,表示在查询下方至少写过关于书籍使用情况的作者总数
select count(*) as author_count from Author where exists (select 1 from Book where Book.AuthorID = Author.AuthorID)
答案 2 :(得分:1)
假设要求统计至少拥有一本书的作者,那么满足该要求的最简单查询是:
SELECT COUNT(DISTINCT b.authorid)
FROM book b
我们可能想为返回的列分配一个别名(名称):
SELECT COUNT(DISTINCT b.authorid) AS `count_of_authors_who_have_at_least_one_book`
FROM book b
我们还可以联接到author
表,但这在这里不是必需的,除非authorid
表中没有出现book
的值author
表(例如,没有外键约束,或者未强制执行参照完整性)
要获取拥有两本书或更多本书的作者的查询会稍微复杂一些:
SELECT COUNT(*)
FROM ( -- authors of two or more books
SELECT b.authorid
FROM book b
GROUP
BY b.authorid
HAVING COUNT(1) >= 2
) c
如果我们想要的作者只有一本书(不是两本书或更多),我们可以在HAVING
子句中调整条件:
SELECT COUNT(*) AS `count_authors_of_exactly_one_book`
FROM ( -- authors of exactly one book
SELECT b.authorid
FROM book b
GROUP
BY b.authorid
HAVING COUNT(1) = 1
) c