【问题标题】:Update a table using info from a second table and a condition from a third table in Postgresql使用 Postgresql 中第二个表中的信息和第三个表中的条件更新表
【发布时间】:2015-06-06 19:47:19
【问题描述】:

我目前的代码如下

UPDATE product_template
SET 
listprice = product_uom.factor * product_template.list_price
FROM product_uom
INNER JOIN product_template ON product_uom.id = product_template.uom_id
INNER JOIN product_product ON product_product.id = product_template.id  
WHERE product_product.manufacturer = 2646 

据我了解,第 1 行指定了我要更新的表。 然后我指定我想使用 2 个数字列更新 product_template 中名为 list_price 的列。 我指定了第二个表,它有一列具有我需要的数值,以便从将要更新的表中更新我的列。 我指定将要更新的表的内部连接以及包含我需要这样做的信息的表。 我将要更新的表与具有我需要的列的表作为更新发生的条件加入。 最后一行说明了在该行中发生更新必须满足的条件。

事实上,如果我尝试在 postgresql 中运行此代码,我会收到以下错误 错误:多次指定表名“product_template”

我只使用 product_template 来指定要更新哪个 tabkle,然后再使用两次来创建内部连接,在使用来自 2 个不同表的信息时更新此表的正确方法是什么?

【问题讨论】:

    标签: database postgresql join sql-update


    【解决方案1】:

    很遗憾,您不能使用JOIN...ON 语法加入正在更新到其余表的表。您必须将这些连接条件移动到 WHERE 子句中,并从 FROM 子句中删除更新后的表本身 product_template

    UPDATE product_template
    SET 
    list_price = product_uom.factor * product_template.list_price
    FROM product_uom, product_product
    WHERE product_product.manufacturer = 2646 and
       product_uom.id = product_template.uom_id and
       product_product.id = product_template.id  
    

    (这是假设您确实想要进行自联接,但您似乎不想这样做。如果您确实想要自联接,那么您需要分配一个表别名,就像非更新自联接一样。)

    【讨论】:

      【解决方案2】:

      阅读此链接:http://www.postgresql.org/docs/9.1/static/sql-update.html

      from_list
      表表达式列表,允许来自其他的列 要出现在 WHERE 条件和更新表达式中的表。 这类似于可以在 SELECT 语句的 FROM 子句。
      请注意,目标表不得出现在 from_list 中,除非您打算进行自连接
      (其中 如果它必须与 from_list 中的别名一起出现)。

      您需要使用别名来为查询中的第二个product_template 分配不同的名称,并在要引用第二个表的地方将product_template 替换为此别名。
      PostgreSql 不知道您在查询中的以下位置(第一个或第二个)中指的是哪个product_template。我也不知道。

      UPDATE product_template
      SET ....... * product_template.list_price
      ...........
      INNER JOIN product_template ON ...... = product_template.uom_id
      INNER JOIN  ..........  ON ...... = product_template.id  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-12
        • 1970-01-01
        相关资源
        最近更新 更多