[英]Simple mysql join not working right
我有
SELECT country.* , COUNT( country.coid ) AS city_count_for_country
FROM `air_countries` AS country
JOIN `air_cities` AS city ON city.coid = country.coid
但它只会返回一个国家/地区,city_count_for_country不会计算一个国家/地区的所有城市,而是所有城市。 怎么了?
谢谢
您想要的只有通过group by
关键字才能实现; 单独的JOIN
永远不会聚合行; 你可能想写
SELECT country.* , COUNT( country.coid ) AS city_count_for_country
FROM air_countries AS country
JOIN air_cities AS city
ON city.coid = country.coid
GROUP BY country.coid
您需要将其分组
SELECT country.* , COUNT( country.coid ) AS city_count_for_country
FROM `air_countries` AS country
JOIN `air_cities` AS city ON city.coid = country.coid
GROUP BY country.coid
通过添加到查询中,尝试使用分组功能
GROUP BY country.coid
您缺少GROUP BY
子句。 尝试这个:
select country.coid, count(*) as city_count_for_country
from `air_countries` as country
join `air_cities` as city on city.coid = country.coid
group by country.coid;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.