測試數據:
/*
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:[email protected], @rownum) AS rank,
@prev:=CONCAT(sq.score, '_', sq.penalty),
@rownum2:[email protected] + 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;
這裏您需要使用臨時表的工作,因爲你可以」 t更新你正在閱讀的表格。會話結束後,臨時表將自動刪除。
它沒有給出第五等級將推出15 ..它給第三等級 –
@HarshKhandelwal對不起,現在糾正它,並進行測試。對我來說工作得很好。 – fancyPants
你是怎麼測試的? ?對我來說,排名列顯示BLOB數據..我想要的是在這些查詢後,排名列必須具有所描述的排名 –