插入新的排名列错误

时间:2016-07-06 01:51:36

标签: mysql sql-insert rank insert-into mysql-5.6

我们有一个表,TABLE_1:

 DATA
 1
 2
 3
 4
 5
 NULL

我们想要根据DATA列生成RANK列

 DATA,RANK
 1,1
 2,2
 3,3
 4,4
 5,5
 NULL,0

以下是我们的代码:

ALTER TABLE ` TABLE_1`

ADD COLUMN `RANK` DOUBLE NOT NULL AFTER `DATA`;

INSERT INTO TABLE_1

SELECT B.DATA,

CASE WHEN B.DATA IS NULL THEN 0 ELSE @number := @number + 1 

END RANK

FROM TABLE_1 B, (SELECT  @number := 0 AS BOO) C 

ORDER BY B.RANK;

上述查询只会在RANK列中生成0

 DATA,RANK
 1,0
 2,0
 3,0
 4,0
 5,0
 NULL,0

但是,如果我们只运行查询,如下所示没有ALTER TABLE和INSERT INTO,HeidiSQL将返回我们正在寻找的表

SELECT B.DATA,

CASE WHEN B.DATA IS NULL THEN 0 ELSE @number := @number + 1 

END RANK

FROM TABLE_1 B, (SELECT  @number := 0 AS BOO) C 

ORDER BY B.RANK;

上面的脚本将生成我们正在寻找的表

 DATA,RANK
 1,1
 2,2
 3,3
 4,4
 5,5
 NULL,0

任何一位大师都可以启发为什么ALTER TABLE / INSERT INTO不起作用?

SQL小提琴可以在这里找到:

http://sqlfiddle.com/#!9/d2837/2

1 个答案:

答案 0 :(得分:0)

使用内部联接的更新查询

select * from bb;
    +------+
    | data |
    +------+
    |    1 |
    |    2 |
    |    3 |
    | NULL |
    +------+
    4 rows in set (0.00 sec)
    mysql> ALTER TABLE `bb`  ADD COLUMN `RANK` DOUBLE NOT NULL AFTER `DATA`;
    Query OK, 0 rows affected (0.72 sec)
    Records: 0  Duplicates: 0  Warnings: 0


    mysql> UPDATE  bb INNER JOIN (SELECT B.DATA as data ,CASE WHEN B.DATA IS NULL THEN 0 ELSE @number := @number + 1 END RANK  FROM bb B, (SELECT  @number := 0 AS BOO) C ORDER BY B.RANK) TT ON TT.DATA=bb.data set bb.rank=TT.rank;
    Query OK, 3 rows affected (0.04 sec)
    Rows matched: 3  Changed: 3  Warnings: 0

    mysql> select * from bb;
    +------+------+
    | data | RANK |
    +------+------+
    |    1 |    1 |
    |    2 |    2 |
    |    3 |    3 |
    | NULL |    0 |
    +------+------+
    4 rows in set (0.00 sec)