加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

PostgreSQL中更新语句中的内部联接

发布时间:2020-12-13 16:17:22 所属栏目:百科 来源:网络整理
导读:我有一个名为temp_table的表,它由以下行组成: cola colb result ---------------- p4 s1 0 p8 s1 0 p9 s1 0 p5 f1 0 p8 f1 0 现在我需要使用colb的count(*)更新结果列.我正在尝试以下查询: update tem_tableset result = x.resultfrom tem_table ttinner j
我有一个名为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 colb,count(*) as result from tem_table group by colb) x
on x.colb = tt.colb;

并从temp_table中选择不同的colb和结果:

select distinct colb,result from tem_table;

获得输出:

colb result
-----------
 s1    3
 f1    3

但预期的产出是:

colb result
-----------
 s1    3
 f1    2

我没有得到我在查询中出错的地方?请帮帮我.谢谢

您不应该重复要在from子句中更新的表.这将创建一个笛卡尔自连接.

从手册中引用:

Note that the target table must not appear in the from_list,unless you intend a self-join (in which case it must appear with an alias in the from_list)

(强调我的)

不幸的是,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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读