简单的mysql连接不能正常工作

时间:2011-12-06 14:26:25

标签: mysql 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

但它只返回一个国家/地区而city_count_for_country不计算一个国家/地区的所有城市,而只计算所有城市。怎么了?

由于

4 个答案:

答案 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;