如何选择和分组四个MySQL表的查询结果?
问题描述:
这些表是这样的:如何选择和分组四个MySQL表的查询结果?
companies
companyid name description
stations
company_id province_id
provinces
provinceid country_id province
countries
countryid country
如何显示在每个国家的企业数量?
我想:
SELECT country, COUNT(companyid)
FROM companies
LEFT JOIN stations ON company_id=companyid
LEFT JOIN provinces ON stations.province_id=provinces.country_id
LEFT JOIN countries ON provinces.country_id=countryid
GROUP BY country
但是我得到的是国名加上电台在该国,而不是总的公司在每个国家的数量。
答
SELECT country, COUNT(distinct companyid)
FROM stations
JOIN provinces ON stations.province_id=provinces.country_id
JOIN countries ON provinces.country_id=countryid
GROUP BY country
1.you根本无需使用左侧加入,因为必须有没有ID错过加盟
2,如果一个公司能够比设置1台更在一省或一个国家,你应该使用distinct
关键字告诉sql计数重复项只有一次在同一组
3.如果你不需要公司名称表的信息,只是不加入它
组由公司名称以及组。 – 2015-03-31 09:11:19