没有ID的查询的SQL更新语句获取ID

时间:2017-03-01 16:18:01

标签: mysql sql

我有一张如下表所示的表格。

我需要更新没有second_id(second_id = 0)的每一行。

但是只有Status为0且second_id的每一行都是0,然后我必须使用来自Record的最后一行的最后一个second_id值和second_id,并将此second_id作为id,并将auto_increments放到所有记录中,其中second_id = 0,状态为0。

在下表中,只会更新ID为5的记录,而second_id为6(last second_id为5 + 1)。

这只能用于SQL Statment吗?

+------+------------+---------+---------+--------+
| id   | second_id  | y       | z       | status |
+------+------------+---------+---------+--------+
|    1 |        3   |      ja | 1       |   0    |
|    2 |        4   |     jaa | 2       |   0    |
|    3 |        5   |      ja | 1       |   0    |
|    4 |        0   |    jaaa | 3       |   1    |
|    5 |        0   |     jaa | 2       |   0    |
|    6 |        0   |   aaaaa | 2       |   0    |
+------+------------+---------+---------+--------+

更新后的结果:

+------+------------+---------+---------+--------+
| id   | second_id  | y       | z       | status |
+------+------------+---------+---------+--------+
|    1 |        3   |      ja | 1       |   0    |
|    2 |        4   |     jaa | 2       |   0    |
|    3 |        5   |      ja | 1       |   0    |
|    4 |        0   |    jaaa | 3       |   1    |
|    5 |        6   |     jaa | 2       |   0    |
|    6 |        7   |   aaaaa | 2       |   0    |
+------+------------+---------+---------+--------+

1 个答案:

答案 0 :(得分:0)

以下SQL将按您的要求执行:

MS SQL:

DECLARE @I INT = (SELECT TOP 1 SECOND_ID FROM TESTTABLE ORDER BY SECOND_ID DESC)

UPDATE TESTTABLE
SET SECOND_ID = @I, @I = @I + 1
WHERE SECOND_ID = 0 AND STATUS = 0

MySQL的:

SET @I := (SELECT second_id FROM MyTable ORDER BY second_id DESC LIMIT 1);

UPDATE MyTable 
SET second_id = @I := @I + 1
WHERE second_id = 0 AND status = 0;

对于单行解决方案,请创建存储过程。

DELIMITER $$

CREATE PROCEDURE RunIncrement()
BEGIN
DECLARE I = (SELECT second_id FROM MyTable ORDER BY second_id DESC LIMIT 1);
UPDATE MyTable 
SET second_id = I := I + 1
WHERE second_id = 0 AND status = 0;
END$$

DELIMITER ;

然后在需要时调用该程序。

CALL RunIncrement();