Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing an UPDATE with Union in SQL

If I were to have these three tables (just an example in order to learn UNION, these are not real tables):

Tables with their columns:

Customer: 
id | name        | order_status

Order_Web:
id | customer_id | order_filled

Order:
id | customer_id | order_filled

And I wanted to update order_status in the Customer table when there is a order filled in either the Order_Web table or the Order table for that customer using Union:

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

How can I combine these two updates using a Union on order_web and order?

Using Microsoft SQL Server Management Studio

like image 368
Jaiesh_bhai Avatar asked Nov 06 '13 17:11

Jaiesh_bhai


1 Answers

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
like image 158
Quassnoi Avatar answered Oct 17 '22 09:10

Quassnoi