通过左连接帮助计数

时间:2010-08-14 14:21:00

标签: mysql count

我有2张桌子

  • 名为 services 的第一个表有 id_service name date
  • 名为 services_images 的第二个表有 id_img img_name id_service

我想做的是获取一个名为 num_images 的行的服务列表,该行计算每个服务有多少图像。

我试过这个

SELECT COUNT(services_images.id_img) as num_images, services.* FROM services
LEFT JOIN services_images ON (services_images.id_service = services.id_service) ORDER BY service.id_service

它不起作用,我不知道如何解决它。这将返回一个服务(第一个id_service:1),其中num_images为 services_images 中所有行的计数!即使将“services_images.id_service = services.id_service”更改为“services_images.id_service = 2”,它仍会显示第一个ID!所以甚至不考虑这个规则。

由于

1 个答案:

答案 0 :(得分:1)

添加GROUP BY子句应该可以解决问题

SELECT COUNT(services_images.id_img) as num_images, services.* 
FROM services
LEFT JOIN services_images ON (services_images.id_service = services.id_service) 
GROUP BY service.id_service
ORDER BY service.id_service

这将按服务对行进行分组,计数聚合将为您提供每个服务的图像数。