web-dev-qa-db-ja.com

SQLでUnionを使用してUPDATEを実行する

これらの3つのテーブルがある場合(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でUnionを使用して、これら2つの更新を組み合わせるにはどうすればよいですか?

Microsoft SQL Server ManagementStudioの使用

7
Jaiesh_bhai

そのためにUINIONは必要ありません-内部結合を外部結合のペアに置き換えると、次のようになります。

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
12
dasblinkenlight
UPDATE  c
SET     c.order_status = 1
FROM    (
        SELECT  customer_id
        FROM    order_web
        WHERE   order_filled = 1
        UNION
        SELECT  customer_id
        FROM    order
        WHERE   order_filled = 1
        ) o
JOIN    customer c
ON      c.id = o.customer_id
2
Quassnoi

ユニオンクエリをサブクエリに入れることができます。

update customer
c.order_status = 1
where id in 
(union query goes here)
1
Dan Bracuk