使用不同的列更新多个记录
我想知道我是否可以/如何使用单个查询中设置的不同列更新多个记录。
因此,我有一张表
Test {
id integer
name varchar
age integer
}
,然后我有一个test1和测试2的
test1 = Test {id=1, name="Joe"}
test2 = Test {id=2, age=22}
表,即使每个都在更新其他列,也可以有一个查询来更新这两个?
如果我有多个具有相同字段的对象,类似于以下作用:
UPDATE test as t
SET id = u.id, age = u.age, name = u.name
FROM (VALUES (1, 21, 'Ronan'),(2, 65, 'Conor') )
AS u(id, age, name)
WHERE u.id = t.id
有人可以为我清除它吗?我正在使用Postgres如果有所不同
I want to know if I can/how to update multiple records with different columns set in a single query.
So I have a table
Test {
id integer
name varchar
age integer
}
Then for test1 and test 2 i have
test1 = Test {id=1, name="Joe"}
test2 = Test {id=2, age=22}
Is it possible to have a single query to update both of these even though each is updating a different column?
If i have multiple objects that all have the same fields something like the following works:
UPDATE test as t
SET id = u.id, age = u.age, name = u.name
FROM (VALUES (1, 21, 'Ronan'),(2, 65, 'Conor') )
AS u(id, age, name)
WHERE u.id = t.id
Anyone able to clear this up for me? Im using Postgres if that makes a difference
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
更新总是设置列出的每一列,没有列出。因此,没有直接的方法在单个语句中更新不同的列。但是,您可以通过指定不想更新的列来指定
null
间接执行此操作值为null)。类似:(参见159E9021D786B89034B3C4B3C44444E4E9BD2755如果需要在几个列和/或行上,这可能会变得很混乱。对于特定列的特定更新似乎既容易又更安全。
An update always sets each column listed and none not listed. So there is no direct way of updating different columns in a single statement0. However you can do so indirectly by specifying
null
for the columns you do not want updated then using thecoalesce
function to set those columns to their existing values (it cannot however set a value to null). Something like: (see demo)The question becomes: Is it really worth it? This could become quite messy if needed on more than a couple columns and/or rows. Seems specific updates for specific columns is both easier and safer.