【问题标题】:PostgreSQL problem with a updating request between two tables两个表之间更新请求的PostgreSQL问题
【发布时间】:2022-01-26 14:13:57
【问题描述】:

我正在尝试在 Postgres(使用 pgadmin4,版本 5.5)中更新具有经典连接请求的表,但它不起作用。 见代码:

我想从表 bof.col 更新列 labcommune 使用表 bof.libcom 中的列 lib_com

当我执行一个简单的穿越请求时:

select c.insee c_insee, c.lab_commune, l.insee l_insee, l.lib_com
from bof.col as c
join bof.libcom as l
on c.insee=l.insee

没问题,返回的是:

c_insee  lab_commune  l_insee lib_com 
01343  Saint-Cyr-sur-Menthon  01343 Saint-Cyr-sur-Menthon 
01346  Saint-Didier-d'Aussiat  01346 Saint-Didier-d'Aussiat 
01348  Saint-Didier-sur-Chalaronne  01348 Saint-Didier-sur-Chalaronne 
01349  Saint-�loi  01349 Saint-Éloi 
01350  Saint-�tienne-du-Bois  01350  Saint-Étienne-du-Bois 

->bof.col 的每一项都与lib_com 的右项交叉

但是当你尝试更新语句时:

 update bof.col
   set lab_commune=l.lib_com
   from bof.col as c
   join bof.libcom as l
   on c.insee=l.insee

我在 bof.col 中有这个返回

insee  lab_commune
01343  Saint-Cyr-sur-Menthon
01346  Saint-Cyr-sur-Menthon
01348  Saint-Cyr-sur-Menthon
01349 Saint-Cyr-sur-Menthon
01350  Saint-Cyr-sur-Menthon

->Item 'Saint-Cyr-sur-Menthon' 在所有行中都是重复的。 我怎么没看到?

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    UPDATE 语句的语法与 SELECT 语句的语法不同。
    不应在 FROM 子句中再次引用更新后的表,而应使用 WHERE 子句代替 ON 子句。
    这就是在 Postgresql 中使用 UPDATE 语句进行隐式连接的方法:

    update bof.col as c
    set lab_commune = l.lib_com
    from bof.libcom as l
    where c.insee = l.insee;
    

    【讨论】:

    • 当然,你是对的!有时我们需要睡个好觉!谢谢你的回复。
    • @FredGina 很好,如果它有帮助,别忘了点击复选标记接受答案。
    猜你喜欢
    • 1970-01-01
    • 2021-06-18
    • 2021-03-03
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多