从连接表中获取子项的总记录

时间:2016-10-03 06:57:46

标签: mysql sql mariadb

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

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

这是表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     | ... |
+----+-------+-------+-----+

2 个答案:

答案 0 :(得分:6)

您需要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

答案 1 :(得分:1)

说明您可以使用以下查询

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;