SQL JOIN - 对所有左侧行进行分组
SQL JOIN - taking all left rows with grouping
所以,我有名为 files 和 folders 的表,它们具有 ID 和它们之间的通常关系:file.folder_id = folder.id
此外,files/folders 中的一些可以被字段 ignore 忽略。
我正在尝试获取文件夹列表和相应文件夹中的文件数。
我的第一种方法运行良好但遗漏了空文件夹:
SELECT folders.id, folders.name, count(files.id) kount
FROM folders, files
WHERE folders.site_id=111
AND files.ignored=0
AND folders.ignored=0
AND files.site_id=111
AND files.folder_id=folders.id
GROUP BY folders.name
ORDER BY folders.name
所以我寻找 LEFT JOIN
SELECT folders.id, folders.name, count(files.id) kount
FROM folders
LEFT JOIN files
ON files.folder_id=folders.id
WHERE folders.site_id=111
AND folders.ignored=0
AND files.ignored=0
AND files.site_id=111
GROUP BY folders.name
ORDER BY folders.name
但同样 - 缺少空文件夹。我做错了什么?
需要把条件过滤加入的table直接放到left join
SELECT folders.id, folders.name, count(files.id) kount
FROM folders
LEFT JOIN files ON files.folder_id=folders.id
AND files.ignored=0
AND files.site_id=111
WHERE folders.site_id=111
AND folders.ignored=0
GROUP BY folders.name
ORDER BY folders.name
试试这个。
SELECT folders.id, folders.name, count(files.id) kount
FROM folders
LEFT JOIN files
ON files.folder_id=folders.id
AND files.ignored=0
AND files.site_id=111
WHERE folders.site_id=111
AND folders.ignored=0
GROUP BY folders.name
ORDER BY folders.name
所以,我有名为 files 和 folders 的表,它们具有 ID 和它们之间的通常关系:file.folder_id = folder.id
此外,files/folders 中的一些可以被字段 ignore 忽略。
我正在尝试获取文件夹列表和相应文件夹中的文件数。 我的第一种方法运行良好但遗漏了空文件夹:
SELECT folders.id, folders.name, count(files.id) kount
FROM folders, files
WHERE folders.site_id=111
AND files.ignored=0
AND folders.ignored=0
AND files.site_id=111
AND files.folder_id=folders.id
GROUP BY folders.name
ORDER BY folders.name
所以我寻找 LEFT JOIN
SELECT folders.id, folders.name, count(files.id) kount
FROM folders
LEFT JOIN files
ON files.folder_id=folders.id
WHERE folders.site_id=111
AND folders.ignored=0
AND files.ignored=0
AND files.site_id=111
GROUP BY folders.name
ORDER BY folders.name
但同样 - 缺少空文件夹。我做错了什么?
需要把条件过滤加入的table直接放到left join
SELECT folders.id, folders.name, count(files.id) kount
FROM folders
LEFT JOIN files ON files.folder_id=folders.id
AND files.ignored=0
AND files.site_id=111
WHERE folders.site_id=111
AND folders.ignored=0
GROUP BY folders.name
ORDER BY folders.name
试试这个。
SELECT folders.id, folders.name, count(files.id) kount
FROM folders
LEFT JOIN files
ON files.folder_id=folders.id
AND files.ignored=0
AND files.site_id=111
WHERE folders.site_id=111
AND folders.ignored=0
GROUP BY folders.name
ORDER BY folders.name