MySql,在DELETE更新计数器后不包含任何空格
作者:互联网
我有一个这样的mySql表(简体)
Id*| Text | Pos (integer)
-----------
A | foo | 0
B | bar | 1
C | baz | 2
D | qux | 3
现在,删除一行后,我想更新其余行的Pos值,这样就不会发现“空洞”或缝隙.
例如,如果我删除Id =’C’的行,则剩余表应为:
Id*| Text | Pos (integer)
-----------
A | foo | 0
B | bar | 1
D | qux | 2
在单个查询中有可能吗?
更新
根据公认的答案,这是我的问题的解决方案:
START TRANSACTION;
SELECT @A:=pos FROM table_name WHERE Id= 'C';
DELETE FROM table_name WHERE Id = 'C';
UPDATE table_name SET Pos = Pos - 1 WHERE Pos > @A;
COMMIT;
解决方法:
您可以通过在表上创建一个AFTER DELETE TRIGGER来实现此目的,
或使用交易:
START TRANSACTION;
SELECT Pos
INTO @var_pos
FROM table_name
WHERE id = 'C';
DELETE
FROM table_name
WHERE id = 'C';
UPDATE table_name
SET Pos = Pos - 1
WHERE Pos > @var_pos;
COMMIT;
标签:delete-row,sql-update,mysql 来源: https://codeday.me/bug/20191127/2075882.html