Database Reference
In-Depth Information
Using
UNION
is simple enough. All you do is specify each
SELECT
statement
and place the keyword
UNION
between each.
Let's look at an example. You need a list of all products costing
5
or less. You
also want to include all products made by vendors
1001
and
1002
, regardless
of price. Of course, you can create a
WHERE
clause that does this, but this time
we use a
UNION
instead.
As just explained, creating a
UNION
involves writing multiple
SELECT
state-
ments. First look at the individual statements:
▼
Input
SELECT vend_id, prod_id, prod_price
FROM products
WHERE prod_price <= 5;
▼
Output
+---------+---------+------------+
| vend_id | prod_id | prod_price |
+---------+---------+------------+
| 1003 | FC | 2.50 |
| 1002 | FU1 | 3.42 |
| 1003 | SLING | 4.49 |
| 1003 | TNT1 | 2.50 |
+---------+---------+------------+
▼
Input
SELECT vend_id, prod_id, prod_price
FROM products
WHERE vend_id IN (1001,1002);
▼
Output
+---------+---------+------------+
| vend_id | prod_id | prod_price |
+---------+---------+------------+
| 1001 | ANV01 | 5.99 |
| 1001 | ANV02 | 9.99 |
| 1001 | ANV03 | 14.99 |
| 1002 | FU1 | 3.42 |
| 1002 | OL1 | 8.99 |
+---------+---------+------------+