我遇到sql查询问题我将首先绘制数据库结构草图:
id | userid | City
------------------------
1 | 1 | New York
2 | 1 | Washington
3 | 1 | New York
4 | 1 | Miami
5 | 2 | New York
4 | 1 | Ney York
5 | 1 | Miami
这是它的样子, userid链接到用户帐户。
我想得到的是以下内容: 如果我查询用户标识1,我想获得该用户的5个最常见城市的列表,并计算其数量;在这种情况下,它将是
Counts | City
------------------------
3 | New York
2 | Miami
1 | Washington
我已经尝试过了:
SELECT count(city), city FROM cities WHERE userid = '1' GROUP BY city ORDER BY count(city) DESC LIMIT 5
但这只列出了一个列表:
Counts | City
------------------------
1 | New York
1 | New York
1 | New York
1 | Miami
1 | Miami
感谢adventage!
答案 0 :(得分:1)
您的查询:
SELECT count(city), city
FROM cities
WHERE userid = '1'
GROUP BY city
ORDER BY count(city) DESC
LIMIT 5;
对于您想要做的事情是正确的。如果您在不同的行上获得相同的城市,那么您可能遇到了数据问题。例如,在城市名称之后可能有不可打印的字符看起来像空格,但不是。一种说法是通过划分城市名称并查看其长度,例如:
SELECT count(city), concat('"', city, '"'), length(city)
FROM cities
WHERE userid = '1'
GROUP BY city
ORDER BY count(city) DESC
LIMIT 5;
答案 1 :(得分:0)
你想要计算id
的..
SELECT count(id), city
FROM cities
WHERE userid = '1'
GROUP BY city
ORDER BY count(id) DESC
LIMIT 5