PostgreSQL 8.4 使用聚合函数更新列
我有两个表,“Hello”和“World”:
“Hello”有两列 id(int) 和 id1(int, 默认值 0)
“World”有 id2(int) 列
每当 id = id2 我想+1 到 id1。
我尝试使用 UPDATE 像这样
UPDATE "Hello" z1 set id1=z1.id1 + 1 FROM "World" z2 WHERE
z1.id = z2.id2
但是将每一列更改为 1 而不是每次出现 id=id2 时添加 1 在寻找解决方案后,我似乎需要使用聚合函数,但是 从以前的帖子中我知道更新中不允许这样做。
我对一个解决方案有一个模糊的想法,我得到每个 id id=id2 的总和,然后将其放入临时表中,然后根据该值进行更新,但我似乎无法将其放在一起,所以我想这可能不是解决问题的最佳途径吗?
I have two tables, "Hello" and "World":
"Hello" has two columns id(int) and id1(int, default value 0)
"World" has column id2(int)
Whenever id = id2 I would like to +1 to id1.
I tried this using UPDATE like so
UPDATE "Hello" z1 set id1=z1.id1 + 1 FROM "World" z2 WHERE
z1.id = z2.id2
But that changed every column to 1 instead of adding 1 for every occurance of id=id2
After looking around for a solution it seems I need to use an aggregate function but
from previous posts I know that isn't allowed within UPDATE.
I have a vague idea of one solution where I get the sum for id=id2 per id then put it in a temporary table and then UPDATE based on that value but I can't seem to put it together so I'm thinking that might not be the best path to a solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是我所做的:
初始化
开头的表格
t1:
t2
测试用例 1:
结果就是你所描述的,即 t1
我怀疑原因此结果是,在
z1.n + 1
中,z1.n
的值仅在开始时确定,并且不会随着更多行匹配而更新。这样,结果就相当于执行SELECT
select *, t1.n + 1 from t1,t2 where t1.id = t2.id;
select *, t1.n + 1 from t1,t2 where t1.id = t2.id;请注意,如果至少有一行
t1.id = t2.id
为 true,则每次UPDATE
都会将 n 中的所有值加一。测试用例 2:
结果符合您的预期,即 t1
请注意,如果表
t2
尚未更新,则每次UPDATE
后最终结果都是相同的修改的。Here's what I did:
Initialization
Tables at the beginning
t1:
t2
Test case 1:
Result is what you described i.e. t1
I suspect the reason for this result is that in
z1.n + 1
the value ofz1.n
is determined only at the beginning and it is not updated as more rows match. This way the result is equivalent to the one you get by executing aSELECT
select *, t1.n + 1 from t1,t2 where t1.id = t2.id;
Please note that every
UPDATE
will increment all values in n by one if there are at least one row for whicht1.id = t2.id
is true.Test case 2:
Result was what you expected i.e. t1
Please note that the end result is same after each
UPDATE
if the tablet2
has not been modified.