测试数据:
/*
drop table test;
create table test (roll int, score int, penalty int);
insert into test (roll, score, penalty) values (11, 3, 23), (12, 3, 20), (13, 3, 20), (14,3,20), (15, 2, 10);
*/
它来了:
ALTER TABLE test ADD COLUMN `rank` int FIRST;
CREATE TEMPORARY TABLE tmp_test LIKE test;
INSERT INTO tmp_test (`rank`, roll, score, penalty)
SELECT cast(q.`rank` as unsigned integer) as `rank`, roll, score, penalty FROM (
SELECT IF(@prev != CONCAT(sq.score, '_', sq.penalty), @rownum:=@rownum2, @rownum) AS rank,
@prev:=CONCAT(sq.score, '_', sq.penalty),
@rownum2:=@rownum2 + 1,
sq.*
FROM (
SELECT
roll, score, penalty
FROM
test
, (SELECT @rownum:=0, @prev:='', @rownum2:=1) r
ORDER BY score DESC, penalty DESC
) sq
) q;
UPDATE test t INNER JOIN tmp_test tt ON t.roll = tt.roll AND t.score = tt.score AND t.penalty = tt.penalty
SET t.rank = tt.rank;
/*optionally...*/
DROP TABLE tmp_test;
您需要在此处使用临时表,因为您无法更新正在读取的表。会话结束时将自动删除临时表。