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

时间:2018-10-15 11:13:55

标签: mysql sql mysql-workbench

我在这里有此用户表: (我想根据分数更新排名)

这是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

1 个答案:

答案 0 :(得分:1)

在MySQL中,您可以通过先设置变量 然后在Public Sub main2() Dim ft As Range Dim ws As Excel.Worksheet Set ws = Application.ActiveSheet Set ft = ws.Range("b2:b365") ecco2 = ecco(ft) End Sub Function ecco(ft As Range) As Long Dim x As Variant Dim L As Long Dim H As Long Dim netarray() As Long For Each x In ft If ft = "st" Then L = x.Offset(0, 1) * x.Offset(0, 3) Else ecco = 0 End If ecco = L ReDim Preserve netarray(L) netarray(L) = L + 1 Next x For i = LBound(netarray) To UBound(netarray) ActiveSheet.Range("o2").Offset(1, 0).Select Next i End Function 中使用ORDER BY来使用变量:

UPDATE

Here是一个SQL提琴。