执行每一行后,Mysql重置变量

时间:2015-04-17 01:48:19

标签: mysql

这是我当前的mysql语句:

SET @rownum := 0;
SELECT school_id, 
       mb_no AS student_id,
       xp, 
       @rownum := @rownum + 1 AS rank_school_position
FROM users 
WHERE school_id IN (
       SELECT school_id 
       FROM users) 
ORDER BY xp DESC;

这是示例表

CREATE TABLE `users` (
`school_id` INT(11) NOT NULL DEFAULT '0',
`mb_no` INT(11) NOT NULL DEFAULT '0',
`xp` INT(10) NOT NULL DEFAULT '0')

和我的示例数据

INSERT INTO `d_copy` (`school_id`, `mb_no`, `xp`) VALUES
(610, 1, 1190),
(610, 2, 195),
(611, 3, 0),
(610, 4, 35),
(610, 5, 160),
(611, 6, 0),
(610, 7, 175),
(611, 8, 0),
(610, 9, 95),
(610, 10, 4770);

如何在每次执行@rownum时将0重置回SELECT school_id FROM users

我的预期输出将是这样的

enter image description here

1 个答案:

答案 0 :(得分:1)

将变量初始化移到from子句中:

SELECT school_id, 
       mb_no AS student_id,
       xp, 
       @rownum := @rownum + 1 AS rank_school_position
FROM users, (SELECT @rownum := 0) q
WHERE school_id IN (
       SELECT school_id 
       FROM users) 
ORDER BY xp DESC;

修改

我只是顿悟了,我想我想出了你想要的东西。这是你的答案:

SELECT school_id, 
       mb_no AS student_id,
       xp, 
       if(@prevschool = school_id, 
          @rownum := @rownum + 1, 
          case when @prevschool := school_id then @rownum := 1 end) AS rank
FROM users
WHERE school_id IN (
       SELECT school_id 
       FROM users) 
ORDER BY school_id asc, xp DESC;

sqlfiddle

另一方面 - 整个where子句是多余的,可以删除。同样如评论中所指出的那样,它不会处理school_id 0

SELECT school_id, mb_no AS student_id, xp, if(@prevschool = school_id, @rownum := @rownum + 1, case when @prevschool := school_id then @rownum := 1 else @rownum := 1 end) AS rank_school_position FROM users ORDER BY school_id asc, xp DESC; 的(奇怪)情况
{{1}}