从已连接 table 中获取 children 的总记录

Get total records of children from connected table

我使用的是 MariaDB 5.5,但对于此解决方案,它与 MySQL 相同。我有两个 table,第一个包含图库,第二个包含每个图库中的文件信息。这是 table gallery:

的示例
+----+-------+-----+
| id | name  | ... |
+----+-------+-----+
| 1  | test1 | ... |
| 2  | test2 | ... |
| 3  | test3 | ... |
| 4  | test4 | ... |
+----+-------+-----+

这是 table gallery_items:

的示例
+----+------+------------+-----+
| id | file | gallery_id | ... |
+----+------+------------+-----+
| 1  | img1 | 3          | ... |
| 2  | img2 | 2          | ... |
| 3  | img3 | 2          | ... |
| 4  | img4 | 1          | ... |
+----+------+------------+-----+

所以我尝试了这段代码:

SELECT gallery.*, COUNT(gallery_items.id) AS items FROM gallery JOIN gallery_items WHERE gallery_items.gallery_id = gallery.id;

嗯,我不太擅长数据库,所以这就是我寻求帮助的原因。这是我的预期结果:

+----+-------+-------+-----+
| id | name  | items | ... |
+----+-------+-------+-----+
| 1  | test1 | 1     | ... |
| 2  | test2 | 2     | ... |
| 3  | test3 | 1     | ... |
| 4  | test4 | 0     | ... |
+----+-------+-------+-----+

您需要 GROUP BY 才能使 COUNT 正常工作

SELECT gallery.*, COUNT(gallery_items.id) AS items FROM gallery 
LEFT JOIN gallery_items ON gallery_items.gallery_id = gallery.id
GROUP BY gallery.id, gallery.name

描述您可以使用以下查询

SELECT
  g.*,COUNT(gi.id) AS items
FROM
  gallery g
LEFT JOIN gallery_items gi
ON g.id = gi.gallery_id
GROUP BY g.id;