sql swap主键值

时间:2010-05-11 12:25:26

标签: sql primary-key swap

是否可以在两个数据集之间交换主键值?如果是这样,那怎么会这样做?

3 个答案:

答案 0 :(得分:11)

为简单起见,假设您有两条记录

id   name
---------
1    john

id   name
---------
2    jim

来自表t(但它们可以来自不同的表)

你可以做到

UPDATE t, t as t2
SET t.id = t2.id, t2.id = t.id
WHERE t.id = 1 AND t2.id = 2

注意: 更新主键有其他副作用,可能首选的方法是保留主键,并交换所有其他列的值。

警告: t.id = t2.id, t2.id = t.id之所以有效,是因为在SQL中,更新发生在事务级别上。 t.id不是变量,=不是赋值。您可以将其解释为“将t.id设置为查询效果之前的值t2.id,将t2.id设置为查询效果之前的值t.id”。但是,某些数据库可能无法正常隔离,例如,请参阅此question(但是,运行上面的查询,可能被认为是多表更新,根据mysql中的标准运行)。

答案 1 :(得分:5)

我更喜欢以下方法(Justin Cave在某处写得类似):

update MY_TABLE t1
set t1.MY_KEY = (case when t1.MY_KEY = 100 then 101 else 100 end)
where t1.MYKEY in (100, 101)

答案 2 :(得分:1)

与@ Bart的解决方案类似,但我采用了稍微不同的方式:

update t
set t.id=(select decode(t.id, 100, 101, 101, 100) from dual)
where t.id in (100, 101);

这是完全相同的,但我知道decodecase更好。

另外,要让@ Bart的解决方案为我工作,我必须添加when

update t
set t.id = (case when t.id = 100 then 101 else 101 end)
where t.id in (100, 101);
相关问题