我有一个像这样的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;
答案 0 :(得分:2)
您可以通过在表格上创建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;
答案 1 :(得分:1)
我认为这应该有效,(我还没有测试过) 您可以在任何删除后运行此语句
update t set t.Pos=a.iterator
from tablename t
join(
SELECT @i:=@i+1 AS iterator, t.id
FROM tablename t,(SELECT @i:=0) r)a
on a.id=t.id