如何用一个sql查询更新多行?(使用“order by”)

2nc8po8w  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(398)

我这里有一个用户表:(我想根据分数更新排名)
下面是sql fiddle:
http://sqlfiddle.com/#!9/2f459d/1/0号
代码审查:

create table users2 (  
     ranking int ,
     user_id int auto_increment primary key, 
     user_n varchar(70) charset utf8mb4 not null comment 'username',
     score int default '0' null, 
     constraint username  
     unique (user_n)  );

具有值:

INSERT INTO users2 (user_id, user_n, score)
value(1,'mohamad',50),
     (2,'john',100),
     (3,'nik',150),
     (4,'sara',200),
     (5,'tom',250);

我想根据分数更新排名。我可以选择但无法更新:

SELECT c.u_rank,a.user_id,a.user_n,score from users2 a LEFT JOIN (SELECT @s:=@s+1 u_rank,user_id
FROM users2 d,(SELECT @s:=0) as b order by d.score DESC )  AS c
ON a.user_id = c.user_id order by score DESC

我目前的努力:

UPDATE users2 a LEFT JOIN (SELECT @s:=@s+1 u_rank,user_id
 FROM users2 ,(SELECT @s:=0) as b ORDER BY score DESC )  AS c
ON a.user_id = c.user_id  SET a.ranking = c.u_rank
hrysbysz

hrysbysz1#

在mysql中,可以通过先设置变量,然后使用 ORDER BYUPDATE :

SET @s := 0;

UPDATE users2 u
    SET u.ranking = (@s := @s + 1)
    ORDER BY score DESC ;

这是一个sql小提琴。

相关问题