我有两张桌子
documents: id, folder_id
folders: id, title
我想检索文件夹列表以及与该文件夹相关的文件数量(documents.folder_id = folders.id)
我试过这个
select
f.title, count(d.id) as file_count
from
folders f
left join
documents d on f.id = d.folder_id
但是只返回一行,文件表中的总行数
答案 0 :(得分:2)
您缺少GROUP BY
子句,以便按f.title
返回一行。
select
f.title, count(d.id) as file_count
from
folders f
left join
documents d on f.id = d.folder_id
GROUP BY f.title
请注意,以上将省略空文件夹,我相信。如果您想为空文件夹计算零,请改为使用COUNT(d.*)
:
select
f.title, count(d.*) as file_count
from
folders f
left join
documents d on f.id = d.folder_id
GROUP BY f.title
答案 1 :(得分:1)
SELECT F.id, F.title, COUNT(D.*)
FROM folders AS F
LEFT OUTER JOIN documents AS D ON D.folder_id = F.id
GROUP BY F.id;