sql交换主键值
是否可以在两个数据集之间交换主键值?如果是这样,人们会怎样做呢?
is it possible to swap primary key values between two datasets? If so, how would one do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
是否可以在两个数据集之间交换主键值?如果是这样,人们会怎样做呢?
is it possible to swap primary key values between two datasets? If so, how would one do that?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
为了简单起见,假设您有
来自表 t 的两条记录(但它们可以来自不同的表)
您可以这样做
注意:
更新主键还有其他副作用,也许首选方法是保留主键不变并交换所有其他列的值。
注意事项:
t.id = t2.id, t2.id = t.id
之所以有效,是因为在 SQL 中更新发生在事务级别。t.id
不是变量,=
不是赋值。您可以将其解释为“将 t.id 设置为查询效果之前 t2.id 的值,将 t2.id 设置为查询效果之前 t.id 的值”。但是,某些数据库可能无法进行适当的隔离,例如,请参阅此问题(但是,运行上面的查询,这可能被认为是多表更新,其行为符合 mysql 中的标准)。Let's for the sake of simplicity assume you have two records
both from table t (but they can come from different tables)
You could do
Note:
Updating primary keys has other side effects and maybe the preferred approach would be to leave the primary keys as they are and swap the values of all the other columns.
Caveat:
The reason why the
t.id = t2.id, t2.id = t.id
works is because in SQL the update happens on a transaction level. Thet.id
is not variable and=
is not assignment. You could interpret it as "set t.id to the value t2.id had before the effect of the query, set t2.id to the value t.id had before the effect of the query". However, some databases might not do proper isolation, see this question for example (however, running above query, which is probably considered multi table update, behaved according to the standard in mysql).我更喜欢以下方法(Justin Cave 在某处写过类似的文章):
I prefer the following approach (Justin Cave wrote similar somewhere):
与@Bart的解决方案类似,但我使用了稍微不同的方式:
这是完全相同的,但我知道
decode
比case
更好。另外,为了让 @Bart 的解决方案对我有用,我必须添加一个
when
:Similar to @Bart's solution, but I used a slightly different way:
This is quite the same, but I know
decode
better thencase
.Also, to make @Bart's solution work for me I had to add a
when
:如果您有 FOREIGN_KEYS 并且想要保留 AUTO_INCRMENT
If you have FOREIGN_KEYS and want to preserve AUTO_INCREMENT