在Mysql中:
我表中的城市有重复的值:
座席城市:
Name New York, USA New York, USA Chicago, USA Chicago, USA Chicago, USA Paris, France Nice, France Milan, Italy
该表中的数据格式为:
<city>, <country>
与…一样:
<city><comma><space><country>
表国家:
Name USA France Italy
我想知道每个国家有多少座城市。喜欢:
Country Count USA 2 France 2 Italy 1
因此,我有2个查询:
SELECT count(*) FROM `Cities` WHERE Cities.name LIKE '%, USA%'
但是此值USA应来自:
USA
SELECT * FROM `country`
现在,如何获得所需的表?
带有LEFT JOIN:
LEFT JOIN
select t1.name Country, count(distinct t2.name) Count from country t1 left join cities t2 on t2.name like concat('%, ', t1.name) group by t1.name
结果:
| Country | Count | | ------- | ----- | | France | 2 | | Italy | 1 | | USA | 2 |