更新选择的ID

时间:2018-11-24 11:03:17

标签: sql postgresql

我进行此查询,并返回了88个ID

SELECT DISTINCT so.id
FROM stock_picking sp
                       INNER JOIN stock_move sm ON sp.id = sm.picking_id
                       INNER JOIN procurement_order po ON sm.procurement_id = po.id
                       INNER JOIN sale_order_line sol ON po.sale_line_id = sol.id 
                       INNER JOIN sale_order so ON sol.order_id = so.id

                       INNER JOIN sale_order_invoice_rel so_inv_rel on so.id = so_inv_rel.order_id
                       INNER JOIN account_invoice inv on so_inv_rel.invoice_id = inv.id

    WHERE 

            so.invoice_status = 'to invoice'
            and sp.state = 'done'       
            and inv.state != 'draft'        

现在我想更新这些ID,并像这样尝试了一下,但是出现错误,如何正确执行?

我没有选择,而是尝试了这一行

update so set invoice_status = 'invoiced' but get an error

ERROR:  relation "so" does not exist
LINE 1: update so set invoice_status = 'invoiced'

1 个答案:

答案 0 :(得分:1)

[so]是您为sale_order表设置的别名,并且代码只能在设置了别名的查询中识别它。 话虽如此,如果您运行更新查询,则希望更新sale_order表中的所有行。 要仅更新SELECT查询返回的ID的表,请使用以下命令:

update sale_order set invoice_status = 'invoiced' 
where id in 
(
SELECT DISTINCT so.id
FROM stock_picking sp
                   INNER JOIN stock_move sm ON sp.id = sm.picking_id
                   INNER JOIN procurement_order po ON sm.procurement_id = po.id
                   INNER JOIN sale_order_line sol ON po.sale_line_id = sol.id 
                   INNER JOIN sale_order so ON sol.order_id = so.id

                   INNER JOIN sale_order_invoice_rel so_inv_rel on so.id = 
                   so_inv_rel.order_id
                   INNER JOIN account_invoice inv on so_inv_rel.invoice_id = inv.id

WHERE 

        so.invoice_status = 'to invoice'
        and sp.state = 'done'       
        and inv.state != 'draft'
)