我正在尝试计算用户表中一组不同城市和国家/地区的出现次数.
该表的类似于:
- userid city country
- ------ --------- --------------
- 1 Cambridge United Kingdom
- 2 London United Kingdom
- 3 Cambridge United Kingdom
- 4 New York United States
我需要的是每个城市,国家/地区的列表,其中包含出现次数:
- Cambridge,United Kingdom,2
- London,1
- New York,United States,1
- $array = SELECT DISTINCT city,country FROM usertable
然后在PHP中将其读入数组,并循环遍历数组,运行查询以计算数组中每行的每个匹配项:
- SELECT count(*) FROM usertable
- WHERE city = $array['city']
- AND country = $array['country']
解决方法
- select city,country,count(*)
- from usertable
- group by city,country