我有四张桌子
users ID display_name 1 Name1 2 Name2 3 Name3
用户可以将书籍添加到表格书
books book_id AddedByuserID 1 1 2 1 3 2 4 3
用户也可以将电子书添加到表格电子书
ebooks ebook_id AddedByuserID 1 1 2 2 3 2 4 3
现在,用户只能将书籍添加到他的馆藏(而不是电子书)
collection userID book_id 1 1 1 2 1 3
我需要这样的输出:
display_name books_added ebooks_added books_in_collection Name1 2 1 3 Name2 1 2 2 Name3 1 1 1
这是得到的:
SELECT users.*, COUNT(DISTINCT collection.book_id) AS books_in_collection, COUNT(DISTINCT books.AddedByuserID) AS books_added, COUNT(DISTINCT ebooks.AddedByuserID) AS ebooks_added
FROM users LEFT JOIN collection ON users.ID = collection.userID
LEFT JOIN books ON users.ID = books.AddedByuserID
LEFT JOIN ebooks ON users.ID = ebooks.AddedByuserID
GROUP BY users.ID
ORDER BY display_name ASC
用户display_name显示正确,也显示集合计数,但另外两个计数显示为1。 如果我删除DISTINCT,则收集计数为86,而其他两个计数则不显示。
我尝试了解LEFT加入并阅读教程,但我现在陷入困境。
答案 0 :(得分:2)
我建议使用相关子查询:
select u.*,
(select count(*) from collection c where u.id = c.userId) as books_in_collection,
(select count(*) from books b where u.id = b.AddedByUserId) as books_added,
(select count(*) from ebooks e where u.id = e.AddedByUserId) as ebooks_added
from users u;
我不知道你为什么要过滤掉第三个用户。