如何在PostgreSQL 9.2.13中进行*此特定*更新+加入?

时间:2015-12-09 21:29:08

标签: sql postgresql postgresql-9.2

好的。我知道这个用例already has a question devoted to it here,但我已经尝试了任何语法,我正在绝望。

这是我的疑问:

with ids as (
  select t.id ntid, ot.id otid, p.id npid, op.id opid, ot.company_id ocid, t.company_id ncid
  from product_template t
  inner join product_template ot on t.multicompany_old_id = ot.id
  inner join product_product p on p.product_tmpl_id = t.id
  inner join product_product op on op.product_tmpl_id = ot.id
)
update ol
set product_id = i.npid
from sale_order_line ol
inner join sale_order o on ol.order_id = o.id
inner join product_product p on ol.product_id = p.id
inner join ids i on p.id = i.opid and o.company_id = i.ncid;

我尝试过的变化:

update [sale_order_line] ol
set [ol.]product_id = i.npid
from...

update sale_order_line ol
set ol.product_id = i.npid
inner join ....

update sale_order_line ol
set product_id = i.npid
from sale_order o on ol.order_id = o.id
inner join product_product p on ol.product_id = p.id
inner join ids i on p.id = i.opid and o.company_id = i.ncid
where ol.order_id = o.id;

没有任何作用。有人能帮助我吗? 我想以下简化案例的解决方案也足够了:

update T
set T.value = J.value
from some_table T
inner join joined_table J on J.some_table_id = T.id;

2 个答案:

答案 0 :(得分:1)

试试这个:

WITH ids AS (
    SELECT
        t.id ntid,
        ot.id otid,
        p.id npid,
        op.id opid,
        ot.company_id ocid,
        t.company_id ncid
    FROM product_template t
        INNER JOIN product_template ot ON t.multicompany_old_id = ot.id
        INNER JOIN product_product p ON p.product_tmpl_id = t.id
        INNER JOIN product_product op ON op.product_tmpl_id = ot.id
)
UPDATE sale_order_line
SET product_id = i.npid
FROM sale_order_line ol
    INNER JOIN sale_order o ON ol.order_id = o.id
    INNER JOIN product_product p ON ol.product_id = p.id
    INNER JOIN ids i ON p.id = i.opid AND o.company_id = i.ncid
WHERE sale_order_line.id = ol.id;

我们的想法是,您想要更新的表格在FROM部分之外,为了使更新正确,您需要标记需要使用WHERE更新数据的情况一部分。

答案 1 :(得分:0)

您不需要在FROM //'加入'的更新中添加/加入目标表。列表;它已经在范围表中了。

WITH ids AS (
  SELECT t.id ntid, ot.id otid, p.id npid
        , op.id opid, ot.company_id ocid, t.company_id ncid
  FROM product_template t
  JOIN product_template ot ON t.multicompany_old_id = ot.id 
  JOIN product_product p ON p.product_tmpl_id = t.id
  JOIN product_product op ON op.product_tmpl_id = ot.id 
)
UPDATE sale_order_line ol -- <<-- target table has an alias
SET product_id = i.npid   -- <<-- product_id SHOULD NOT use this alias
FROM ids i 
JOIN sale_order o ON o.company_id = i.ncid;
JOIN product_product p ON p.id = i.opid
WHERE ol.product_id = p.id   -- <<-- target table is linked    
AND ol.order_id = o.id       -- <<-- to the source(s) here
        ;