我正在尝试计算用户表中一组不同城市和国家/地区的出现次数.
该表的类似于:
userid city country
------ --------- --------------
1 Cambridge United Kingdom
2 London United Kingdom
3 Cambridge United Kingdom
4 New York United States
Run Code Online (Sandbox Code Playgroud)
我需要的是每个城市和国家/地区的列表,其中包含出现次数:
Cambridge, United Kingdom, 2
London, United Kingdom, 1
New York, United States, 1
Run Code Online (Sandbox Code Playgroud)
目前我运行SQL查询来获取不同的对:
$array = SELECT DISTINCT city, country FROM usertable
Run Code Online (Sandbox Code Playgroud)
然后在PHP中将其读入数组,并循环遍历数组,运行查询以计算数组中每行的每个匹配项:
SELECT count(*) FROM usertable
WHERE city = $array['city']
AND country = $array['country']
Run Code Online (Sandbox Code Playgroud)
我假设我对SQL缺乏掌握的东西 - 这样做的正确方法是什么,最好没有PHP的干预?
Daw*_*ica 19
select city, country, count(*)
from usertable
group by city, country
Run Code Online (Sandbox Code Playgroud)
你需要的是一组:
Select city, country, count(*) as counter
from usertable
group by city, country
Run Code Online (Sandbox Code Playgroud)