PostgreSQL中update语句的内部联接
我有一个名为temp_table的表,它由以下行组成:PostgreSQL中update语句的内部联接,postgresql,Postgresql,我有一个名为temp_table的表,它由以下行组成: cola colb result ---------------- p4 s1 0 p8 s1 0 p9 s1 0 p5 f1 0 p8 f1 0 现在我需要用colb的count(*)更新结果列。我正在尝试以下查询: update tem_table set result = x.result from tem_table tt inner join(select
cola colb result
----------------
p4 s1 0
p8 s1 0
p9 s1 0
p5 f1 0
p8 f1 0
现在我需要用colb的count(*)更新结果列。我正在尝试以下查询:
update tem_table
set result = x.result
from tem_table tt
inner join(select colb,count(*) as result from tem_table group by colb) x
on x.colb = tt.colb;
并从temp_表中选择不同的colb和结果:
select distinct colb,result from tem_table;
获取输出:
colb result
-----------
s1 3
f1 3
但预期产出是:
colb result
-----------
s1 3
f1 2
我不明白我的问题哪里出错了?请帮帮我。谢谢您不应该在
from
子句中重复要更新的表。这将创建笛卡尔自联接
引自手册:
请注意,目标表不得出现在from_列表中,除非您打算进行自联接(在这种情况下,它必须在from_列表中显示别名)
(强调矿山)
不幸的是,UPDATE
不支持使用JOIN
关键字的显式联接。像这样的方法应该会奏效:
update tem_table
set result = x.result
from (
select colb,count(*) as result
from tem_table
group by colb
) x
where x.colb = tem_table.colb;
伟大的非常感谢你。