- 联合查询:把多个查询语句的查询结果结合在一起
- 主要用法:... union ... (去除重复) ...union all ... (不去重复)
- union查询注意事项:
- 必须有两条或以上的select语句组成。
- 两个select语句查询结果的字段数必须一致。
- 用到order by排序时,需要对子句用括号括起来。
我现有如下表employee:
1、对于注意事项2进行实操:
select * from employee where job='文员' union select empno,ename from employee where job='销售员';
字段数量不一致报错:ERROR 1222 (21000): The used SELECT statements have a different number of columns
那么假如字段数量一致,能不能跨表联合呢? 所以我决定创建一个与employee表一致的表employee1
使用建表复制语句:
create table employee1 as select * from employee;
实验显示是可以查询成功,所以使用union是可以跨表查询的,但前提条件是表结构完全一致。
2、对注意事项3进行实操:
select * from employee where job='文员' order by sal union select * from employee1 where job='销售员' order by sal desc;
没有使用括号报错:ERROR 1221 (HY000): Incorrect usage of UNION and ORDER BY