学习笔记,以代码和例子堆砌而成,方便查阅。
参考书籍:《Mysql必知必会》等
要点:UNION、UNION ALL
此Blog会用到下面2个表.
temp_product2:
# id, pr_id, pro_name, price
'1', '1001', 'Dog', '2000'
'2', '1001', 'Cat', '1500'
'3', '1002', 'Bunny', '100'
'4', '1002', 'Bird', '200'
'5', '1003', 'Fish', '50'
temp_product3:
# id, pr_id, pro_name, price
'1', '1002', 'Pen', '60'
'2', '1002', 'Book', '50'
'3', '1002', 'Rule', '10'
'4', '1003', 'Apple', '5'
'5', '1003', 'Orange', '3'
'6', '1005', 'Toy', '5000'
- 不包含重复行的组合查询
涉及一个表:
SELECT pr_id, pro_name, price
FROM temp_product3 WHERE price<50
UNION
SELECT pr_id, pro_name, price
FROM temp_product3 WHERE pr_id=1002;
查询结果:
# pr_id, pro_name, price
'1002', 'Rule', '10'
'1003', 'Apple', '5'
'1003', 'Orange', '3'
'1002', 'Pen', '60'
'1002', 'Book', '50'
涉及两个表:
SELECT pr_id, pro_name, price
FROM temp_product3 WHERE price<50
UNION
SELECT pr_id, pro_name, price
FROM temp_product2 WHERE pr_id=1001;
查询结果:
# pr_id, pro_name, price
'1002', 'Rule', '10'
'1003', 'Apple', '5'
'1003', 'Orange', '3'
'1001', 'Dog', '2000'
'1001', 'Cat', '1500'
- UNION规则
①UNION必须由两条或两条以上的SELECT语句组成,语句之间用关键字UNION分隔。
②UNION中的每个查询必须包含相同的列,表达式或聚集函数。
③列的数据类型不需要完全相同,但必须兼容。
- 包含重复行的组合查询
SELECT pr_id, pro_name, price
FROM temp_product3 WHERE price<50
UNION ALL
SELECT pr_id, pro_name, price
FROM temp_product3 WHERE pr_id=1002;
查询结果:
# pr_id, pro_name, price
'1002', 'Rule', '10'
'1003', 'Apple', '5'
'1003', 'Orange', '3'
'1002', 'Pen', '60'
'1002', 'Book', '50'
'1002', 'Rule', '10'
- 对组合查询结果进行排序
SELECT pr_id, pro_name, price
FROM temp_product3 WHERE price<50
UNION
SELECT pr_id, pro_name, price
FROM temp_product3 WHERE pr_id=1002
ORDER BY price;
查询结果:
# pr_id, pro_name, price
'1003', 'Orange', '3'
'1003', 'Apple', '5'
'1002', 'Rule', '10'
'1002', 'Book', '50'
'1002', 'Pen', '60'
注意!在用UNION组合查询时,只能使用一条ORDER BY子句,它必须出现在最后一条SELECT语句之后。