我有一个用户表,每个用户总计需要计算每个用户的排名并存储它。
用户表
+----+------+-------+------+
| id | name | total | rank |
+----+------+-------+------+
| 1 | joe | 30 | 0 |
+----+------+-------+------+
| 2 | james| 52 | 0 |
+----+------+-------+------+
| 3 | pia | 44 | 0 |
+----+------+-------+------+
| 4 | jessy| 21 | 0 |
+----+------+-------+------+
预期结果
+----+------+-------+------+
| id | name | total | rank |
+----+------+-------+------+
| 1 | joe | 30 | 3 |
+----+------+-------+------+
| 2 | james| 52 | 1 |
+----+------+-------+------+
| 3 | pia | 44 | 2 |
+----+------+-------+------+
| 4 | jessy| 21 | 4 |
+----+------+-------+------+
目前我可以通过总计来了解他们的排名,但我无法计算每个
的排名SELECT * from users ORDER BY total DESC
答案 0 :(得分:1)
如果您只想根据socket = zmq.Context().socket( zmq.SUB )
socket.connect( 'tcp://192.168.1.17:5555;192.168.1.1:5555' )
列显示排名,则以下查询将有效:
total
另一种类似方法:
select users.*,
@rank := @rank + 1 as Rank
from users
cross join (select @rank := 0) r
order by total desc;
现在,如果您已经在表中初始化为0的排名列,那么您可以使用实际排名更新它,如下所示:
set @rank := 0;
select users.*,
@rank := @rank + 1 as Rank
from users
order by total desc;
希望它有所帮助!
答案 1 :(得分:1)
这是一个没有涉及和用户定义变量的简单查询
select id,name,total,
(
select count(distinct total)
from users b
where a.total < b.total
) +1 rank
from users a
注意上面的查询还要注意,如果多于1个用户具有相同的总数,那么它将分配相同的等级,如demo用户3,5&amp; 6具有相同的总值,因此它们应该得到相同的等级
或者,如果您想更新现有表,可以将更新查询写为
update users a
join (
select id,
(
select count(distinct total)
from users d
where c.total < d.total
) +1 rank
from users c
) b on a.id = b.id
set a.rank = b.rank