【问题标题】:postgresql update a table column based on values stored in another tablepostgresql 根据存储在另一个表中的值更新表列
【发布时间】:2019-07-30 09:39:33
【问题描述】:

我有两张桌子。我想根据另一个名为shiptype_emodnet 的表的emodnet_type 列更新名为2018_01 的表的emodnet_code 列值,并使用其他两个列的值的匹配:来自2018_01 的列aisshiptype表和列aisshiptype 来自shyptype_emodnet 表。查询成功返回但 0 行受影响:

UPDATE "2018_01"
SET emodnet_code = shiptype_emodnet.emodnet_type
FROM "shiptype_emodnet" 
WHERE '2018_01.aisshiptype' = 'shiptype_emodnet.aisshiptype';

【问题讨论】:

  • 你的问题是什么?
  • 对应的SELECT返回什么?
  • 查询成功返回,但有 0 行受到影响,这是不可能的。我的问题是:代码中有错误?
  • 为什么这不可能?如果 SELECT 返回 0 行,则没有与 WHERE 条件匹配的数据。检查一下。
  • 显然这不是“不可能”,因为它显然发生在你​​身上;)

标签: postgresql


【解决方案1】:

您正在比较 WHERE 子句中的字符串常量,not 列。所以你的where子句:

WHERE '2018_01.aisshiptype' = 'shiptype_emodnet.aisshiptype';

始终为 false,因为字符串文字 '2018_01.aisshiptype' 永远不会与字符串文字 'shiptype_emodnet.aisshiptype' 相同。所以你的 where 条件基本上是一样的:

where false

Identifiers 需要用双引号引起来(")。单引号 (') 用于 string literals

UPDATE "2018_01"
  SET emodnet_code = shiptype_emodnet.emodnet_type
FROM "shiptype_emodnet" 
WHERE "2018_01".aisshiptype = shiptype_emodnet.aisshiptype;

对于使用 SQL 中非法名称或使用双引号和混合大小写创建的列或表,您只需要双引号。

【讨论】:

  • @LuigiFalco 如果该答案解决了您的问题,请accept 它,以便您的问题被标记为已解决。
【解决方案2】:

你可以试试:

UPDATE "2018_01" t
SET t.emodnet_code = (SELECT shiptype_emodnet.emodnet_type 
                    FROM shiptype_emodnet 
                    WHERE t.aisshiptype = shiptype_emodnet.aisshiptype
                    Limit 1);

您应该添加limit 1 以更新每一行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 2017-07-24
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多