我有
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不计算一个国家/地区的所有城市,而只计算所有城市。怎么了?
由于
答案 0 :(得分:1)
您想要的只能通过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
答案 1 :(得分:0)
您需要将其分组
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
答案 2 :(得分:0)
尝试使用群组功能,添加到您的查询
GROUP BY country.coid
答案 3 :(得分:0)
你错过了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;