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不計爲一個國家的所有城市,但剛纔的所有城市。怎麼了?
感謝
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
關鍵字實現;單獨從不聚合行;你可能想通過添加到您的查詢
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
嘗試。試試這個:
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;
你缺少GROUP BY
條款使用分組功能,寫
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