我在查询中获得了用户的排名。
表格如下(这里是按点排序):
-----------------
| user | points |
-----------------
paul1 22000
paul 13440
paul5 1400
paul2 1300
paul3 1300
paul4 1300
. .
. .
. .
SELECT user, points
FROM table1
WHERE points>= 1300
HAVING user <= 'paul3' OR points > 1300
ORDER BY points DESC, user ASC
此查询返回我需要的正确数据但我真的只需要行数(本例中为5),所以我尝试修改查询,如下所示:
SELECT COUNT(ID) AS num, user, points
FROM table1
WHERE points>= 1300
HAVING user <= 'paul3' OR points > 1300
ORDER BY points DESC, user ASC
但是在这里它返回num = 6并且我根本不理解为什么。
有什么想法吗?
非常感谢!
答案 0 :(得分:1)
尝试计算所有不同的用户:
SELECT COUNT(DISTINCT user) AS num
FROM table1
WHERE points>= 1300
HAVING user <= 'paul3' OR points > 1300
ORDER BY points DESC, user ASC
答案 1 :(得分:1)
为什么您同时使用where
和having
子句而没有聚合?您的查询等同于:
SELECT user, points
FROM table1
WHERE (user <= 'paul3' and points = 1300) OR (points > 1300)
ORDER BY points DESC, user ASC
如果您想计算行数,请在count(*)
中执行select
:
SELECT COUNT(*)
FROM table1
WHERE (user <= 'paul3' and points = 1300) OR (points > 1300)
ORDER BY points DESC, user ASC;
您的查询未执行所需操作的原因是因为在聚合之后评估了having
子句。它过滤聚合的结果,而不是进入聚合的行。