请问这MySQL quearly select 所有写书的作者?
Will this MySQL quearly select all of the authors who wrote a book?
我在尝试解决这个问题时遇到了很多麻烦
Write a query to show the number of authors who have written a book
Author(AuthorID, AuthorName, Address, TelephoneNo, PublisherCode)
Book (BookID, Name, ReleaseDate, Price, AuthorID)
我有
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;
计算每个作者所写书籍的数量。
这不是我知道的正确的,但我想不通??
你们非常接近。您需要加入作者 ID。您目前混用了作者 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;
如果您只想得到一个数字,表示至少在以下查询中使用书籍的作者总数
select count(*) as author_count from Author where exists (select 1 from Book where Book.AuthorID = Author.AuthorID)
假设要求计算至少拥有一本书的作者,满足该要求的最简单查询是:
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
table 进行连接,但这里没有必要,除非 book
authorid
table 未出现在 author
table 中(即没有外键约束,或者未强制执行参照完整性)
获取拥有两本书或更多书籍的作者的查询会稍微复杂一些:
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
我在尝试解决这个问题时遇到了很多麻烦
Write a query to show the number of authors who have written a book
Author(AuthorID, AuthorName, Address, TelephoneNo, PublisherCode)
Book (BookID, Name, ReleaseDate, Price, AuthorID)
我有
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;
计算每个作者所写书籍的数量。
这不是我知道的正确的,但我想不通??
你们非常接近。您需要加入作者 ID。您目前混用了作者 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;
如果您只想得到一个数字,表示至少在以下查询中使用书籍的作者总数
select count(*) as author_count from Author where exists (select 1 from Book where Book.AuthorID = Author.AuthorID)
假设要求计算至少拥有一本书的作者,满足该要求的最简单查询是:
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
table 进行连接,但这里没有必要,除非 book
authorid
table 未出现在 author
table 中(即没有外键约束,或者未强制执行参照完整性)
获取拥有两本书或更多书籍的作者的查询会稍微复杂一些:
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