联合查询:多个查询语句的查询结果结合在一起
主要语法1:...UNION... (去除重复记录)
主要语法2:...UNION ALL... (不去重复)
注意事项:
两个select语句的查询结果的字段数必须一致;
通常也尽量让两个查询语句的字段类型具有一致性;
可以联合查询更多的查询结果;
用到order by排序时,需要加上limit (加上最大条数就可以),需要对查询子句用括号括起来。
使用:
### 对经理的编号顺序排列,而对销售的编号降序排列mysql> (select * from employee where job = '经理' order by empno limit 999999) union (select * from employee where job = '销售' order by empno desc limit 999999);+-------+-------+------+------------+-------+--------+| empno | ename | job | hiredate | sal | deptnu |+-------+-------+------+------------+-------+--------+| 10002 | 张三 | 经理 | 2020-05-10 | 70000 | 3 || 10003 | 李四 | 经理 | 2020-05-10 | 70000 | 3 || 10005 | 赵六 | 销售 | 2020-05-10 | 70000 | 4 || 10004 | 王五 | 销售 | 2020-05-10 | 70000 | 4 |+-------+-------+------+------------+-------+--------+4 rows in setmysql> select * from employee union select * from employee ;+-------+-------+--------+------------+--------+--------+| empno | ename | job | hiredate | sal | deptnu |+-------+-------+--------+------------+--------+--------+| 10000 | tom | 董事长 | 2020-05-10 | 100000 | 1 || 10001 | jerry | CEO | 2020-05-10 | 80000 | 2 || 10002 | 张三 | 经理 | 2020-05-10 | 70000 | 3 || 10003 | 李四 | 经理 | 2020-05-10 | 70000 | 3 || 10004 | 王五 | 销售 | 2020-05-10 | 70000 | 4 || 10005 | 赵六 | 销售 | 2020-05-10 | 70000 | 4 |+-------+-------+--------+------------+--------+--------+6 rows in setmysql> select * from employee union all select * from employee ;+-------+-------+--------+------------+--------+--------+| empno | ename | job | hiredate | sal | deptnu |+-------+-------+--------+------------+--------+--------+| 10000 | tom | 董事长 | 2020-05-10 | 100000 | 1 || 10001 | jerry | CEO | 2020-05-10 | 80000 | 2 || 10002 | 张三 | 经理 | 2020-05-10 | 70000 | 3 || 10003 | 李四 | 经理 | 2020-05-10 | 70000 | 3 || 10004 | 王五 | 销售 | 2020-05-10 | 70000 | 4 || 10005 | 赵六 | 销售 | 2020-05-10 | 70000 | 4 || 10000 | tom | 董事长 | 2020-05-10 | 100000 | 1 || 10001 | jerry | CEO | 2020-05-10 | 80000 | 2 || 10002 | 张三 | 经理 | 2020-05-10 | 70000 | 3 || 10003 | 李四 | 经理 | 2020-05-10 | 70000 | 3 || 10004 | 王五 | 销售 | 2020-05-10 | 70000 | 4 || 10005 | 赵六 | 销售 | 2020-05-10 | 70000 | 4 |+-------+-------+--------+------------+--------+--------+12 rows in set
最后修改时间:2020-07-01 12:54:29
文章转载自227decision,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




