假设我有发布者的数据库,他们使用作者,撰写图书。
或者用另一种方式来表达,每本图书都是由作者撰写的,他们为发布商工作。
publishers: id
authors: id, publisher_id
books: id, author_id
我知道如何从this question获取每个人都有多少作者的发布商列表。
如何获取每个发布了多少本书的发布商列表?
我如何才能同时获得两个出版商,每个出版商都有作者数量和图书数量?
答案 0 :(得分:2)
试试这个
SELECT COUNT(DISTINCT b.`id`) noofbooks,COUNT(DISTINCT au.id) noofauthers,pub.id publisher FROM publisher pub
INNER JOIN auther au ON au.`pub_id`= pub.`id`
INNER JOIN books b ON b.`aut_id` = au.`id` GROUP BY pub.id
答案 1 :(得分:1)
您需要三个表连接
SELECT publisher.id, count(*) from publisher
INNER JOIN author on publisher.id = author.publisher_id
INNER JOIN book on author.id = book.author_id GROUP BY publisher.id;
答案 2 :(得分:1)
您只需触发一个简单的SQL连接查询,如下所示。
SELECT p.publishers , COUNT(a.authors) totalAuthors, COUNT(b.books) TotalBooks
FROM publishers AS p,authors AS a ,books AS b
WHERE p.publishersid = a.publishersid
AND a.authorsid = b.authorsid
GROUP BY p.publishersid;
答案 3 :(得分:0)
我最终得到了类似于bhanu的回答:
SELECT publishers.*,
COUNT(DISTINCT authors.id) AS 'author_count',
COUNT(DISTINCT books.id) AS 'book_count'
FROM publishers
LEFT JOIN authors ON (authors.publisher_id = publishers.id)
LEFT JOIN books ON (books.author_id = authors.id)
GROUP BY publishers.id;