这是一张表:
mysql> SELECT * FROM test_member order by points asc;
+-----------+---------+
| member_id | points |
+-----------+---------+
| 34 | 1000 |
| 22 | 2000 |
| 33 | 2000 |
| 35 | 3000 |
+-----------+---------+
正确的结果: 当我的member_id是' 35'时,我的排名将是' 1',
当我的member_id为' 22'时,我的排名将为' 2'
当我的member_id为' 33'时,我的排名将为' 2'
当我的member_id是' 34'时,我的排名将是' 3'
...
等等。
尝试 - 1
SELECT * FROM (
SELECT member_id,
@points := @points + 1 AS rank
FROM test_member p, (SELECT @points := 0) r
ORDER BY points DESC
) t
WHERE member_id='33';
+-----------+----------------------------------------+
| member_id | rank |
+-----------+------------+------+---------+----------+
| 33 | 3.000000000000000000000000000000 |
+-----------+----------------------------------------+
尝试 - 2(mysql + php方式)
<?php
$simulation_ponits = 1000;
$sql = '
SELECT t.points, COUNT(*) as count_num
FROM test_member as t
WHERE t.points > ' . $simulation_ponits . '
GROUP BY t.points
HAVING t.points > ' . $simulation_ponits .'
';
$result = mysql_query($sql);
$count_rank = 1;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$count_rank +=$row['count_num'];
}
+--------+-----------+
| points | count_num |
+--------+-----------+
| 2000 | 2 |
| 3000 | 1 |
+--------+-----------+
# $count_rank => 3
两次尝试都只有mysql + php方式才能显示正确的结果, 我可以通过其他方式尝试这样做吗? 提前谢谢。
答案 0 :(得分:0)
您正在尝试获得排名,而不是行号。以下应该有效:
SELECT * FROM (
SELECT member_id,
@rnk := @rnk + if (@prevPoints = points, 0,
if (@prevPoints := points, 1, 1)) as rnk
FROM test_member p, (SELECT @rnk := 0, @prevPoints := null) r
ORDER BY points DESC
) t
WHERE member_id = 33