我有两个与多对多关系相关的实体
客户,服务,clients_has_services。
我需要检索具有各自客户数量的所有服务,如下所示:
服务1 20
Service2 10
Service3 5
Service4 0
....
我在查询时遇到问题,这只会返回一条记录:
SELECT
services.id as id,
services.name as name,
COUNT(clients_has_services.services_id) as ranking
FROM services
LEFT JOIN clients_has_services ON services.id = clients_has_services.services_id
答案 0 :(得分:1)
你需要一个group by子句:
SELECT
services.id as id,
services.name as name,
COUNT(clients_has_services.services_id) as ranking
FROM services
LEFT JOIN clients_has_services ON services.id = clients_has_services.services_id
GROUP BY
services.id,
services.name