一尘不染

在SQL中使用Union执行更新

sql

如果我要拥有这三个表(只是为了学习UNION的一个示例,这些不是真实的表):

带有其列的表:

Customer: 
id | name        | order_status

Order_Web:
id | customer_id | order_filled

Order:
id | customer_id | order_filled

我想在使用Union的那个客户的Order_Web表或Order表中填写订单时,更新Customer表中的order_status:

UPDATE c
SET c.order_status = 1
FROM Customer AS c
INNER JOIN Order_Web As ow
      ON c.id = ow.customer_id
WHERE ow.order_filled = 1

UPDATE c
SET c.order_status = 1
FROM Customer AS c
INNER JOIN Order As o
      ON c.id = o.customer_id
WHERE o.order_filled = 1

如何在order_web和order上使用联合将这两个更新结合在一起?

使用Microsoft SQL Server Management Studio


阅读 159

收藏
2021-05-16

共1个答案

一尘不染

您不需要这样做UNION-用一对外部连接替换内部连接应该做到这一点:

UPDATE c
SET c.order_status = 1
FROM Customer AS c
LEFT OUTER JOIN Order_Web As ow ON c.id = ow.customer_id
LEFT OUTER JOIN Order As o ON c.id = o.customer_id
WHERE ow.order_filled = 1 OR o.order_filled = 1

您还可以使用WHERE EXISTS,如下所示:

UPDATE c
SET c.order_status = 1
FROM Customer AS c
WHERE EXISTS (
    SELECT 1 FROM Order_Web As ow WHERE c.id = ow.customer_id AND ow.order_filled = 1 
) OR EXISTS (
    SELECT 1 FROM Order As o WHERE c.id = o.customer_id AND o.order_filled = 1
)

如果必须使用UNION,则可以执行以下操作:

UPDATE c
SET c.order_status = 1
FROM Customer AS c
WHERE c.id in (
        SELECT ow.id FROM Order_Web As ow WHERE ow.order_filled = 1 
    UNION
        SELECT o.id FROM Order As o WHERE o.order_filled = 1
)

或同一个JOIN

UPDATE c
SET c.order_status = 1
FROM Customer AS c
JOIN (
        SELECT ow.id AS id FROM Order_Web As ow WHERE ow.order_filled = 1 
    UNION
        SELECT o.id AS id FROM Order As o WHERE o.order_filled = 1
) AS ids ON ids.id = c.id
2021-05-16