2011-12-06 29 views
2

簡單的MySQL的聯接不工作的權利

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不計爲一個國家的所有城市,但剛纔的所有城市。怎麼了?

感謝

回答

1

你想要的是僅由group by關鍵字實現;單獨從不聚合行;你可能想通過添加到您的查詢

GROUP BY country.coid 
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 
0

嘗試。試試這個:

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; 
0

你缺少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