SQL基礎 union的用法


一、區別1:取結果的交集

1、union: 對兩個結果集進行並集操作, 不包括重復行,相當於distinct, 同時進行默認規則的排序;

2、union all: 對兩個結果集進行並集操作, 包括重復行, 即所有的結果全部顯示, 不管是不是重復;

二、區別2:獲取結果后的操作

1、union: 會對獲取的結果進行排序操作

2、union all: 不會對獲取的結果進行排序操作

三、區別3:

1、union看到結果中ID=3的只有一條

select * from student2 where id < 4

union

select * from student2 where id > 2 and id < 6

2、union all 結果中ID=3的結果有兩個

select * from student2 where id < 4

union all

select * from student2 where id > 2 and id < 6

四、總結

union all只是合並查詢結果,並不會進行去重和排序操作,在沒有去重的前提下,使用union all的執行效率要比union高


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM