(jlive)[crashcourse]>SELECT vend_id, prod_id, prod_price FROM products WHERE prod_price <= 5 OR vend_id IN (1001,1002);
+---------+---------+------------+
| vend_id | prod_id | prod_price |
+---------+---------+------------+
|
|
|
|
|
|
|
|
+---------+---------+------------+
8 rows in set (0.00 sec)
(jlive)[crashcourse]>SELECT vend_id, prod_id, prod_price FROM products WHERE prod_price <= 5 UNION SELECT vend_id, prod_id, prod_price FROM products WHERE vend_id IN (1001,1002);
+---------+---------+------------+
| vend_id | prod_id | prod_price |
+---------+---------+------------+
|
|
|
|
|
|
|
|
+---------+---------+------------+
8 rows in set (0.00 sec)
UNION只是将完整查询语句查询到的结果整合到了一起并会自动去除重复行,故上面的语句,不使用UNION也可以通过OR来实现,但如果是完完全全地UNION, OR就无法做到,如:
(jlive)[crashcourse]>SELECT vend_id, prod_id, prod_price FROM products WHERE prod_price <= 5 UNION ALL SELECT vend_id, prod_id, prod_price FROM products WHERE vend_id IN (1001,1002);
+---------+---------+------------+
| vend_id | prod_id | prod_price |
+---------+---------+------------+
|
|
|
|
|
|
|
|
|
+---------+---------+------------+
9 rows in set (0.00 sec)
还可进行排序
(jlive)[crashcourse]>SELECT vend_id, prod_id, prod_price FROM products WHERE prod_price <= 5 UNION SELECT vend_id, prod_id, prod_price FROM products WHERE vend_id IN (1001,1002) ORDER BY vend_id, prod_price DESC;
+---------+---------+------------+
| vend_id | prod_id | prod_price |
+---------+---------+------------+
|
|
|
|
|
|
|
|
+---------+---------+------------+
8 rows in set (0.15 sec)