若無特殊說明,oracle與mysql均適用
-
使用場景
union、union all關鍵字用戶將兩個select查詢結果集合并成一個結果集,例如:一個舊系統使用a表,同樣的信息但是新系統使用了b表,這時候可以使用union或者union all關鍵字將舊系統和新系統的數據合并顯示。
-
union和union all的相同點和不同點
- 相同點:都是對兩個查詢結果集進行并集操作。
- 不同點:union會合并重復的行,而union all則不會,所謂重復行即兩行數據所有的查詢字段都相同。
- union all先跟左邊的查詢結果,然后再跟右邊的查詢結果。在oracle中union是全量排序,所謂全量排序即先按照第一個字段排序,然后按照第二個字段排序,依次類推。而在mysql中union先跟左邊的查詢結果,然后再跟右邊的查詢結果
-
使用需要注意點
- 如果不想使用默認的全量排序,可以在sql語句末尾使用order by+數字(排序字段的位置),mysql還可以使用order by+字段的方式
- 關鍵字兩邊查詢的字段要完全一樣
-
擴展補充(mysql不支持)
- Intersect:取兩個結果集的交集,和并重復行。
- Minus:取兩個結果集的差集,即在第一個查詢結果中包含,并且在第二個查詢結果中不包含的數據,合并重復行。
-
DEMO
create table student_a(
id number,
name varchar2(100));create table student_b(
id number,
name varchar2(100));insert into STUDENT_A (id, name)
values (1, '張三');
insert into STUDENT_A (id, name)
values (2, '李四');
insert into STUDENT_A (id, name)
values (1, '張三');
commit;insert into STUDENT_B (id, name)
values (2, '李四');
insert into STUDENT_B (id, name)
values (3, '趙六');
commit;select id,name from student_a
union
select id,name from student_b ;select id,name from student_a
union all
select id,name from student_b ;select id,name from student_a
Intersect
select id,name from student_b ;select id,name from student_a
Minus
select id,name from student_b ;select id,name from student_a
union all
select id,name from student_b order by 1;