當咱們須要將兩個select語句的結果做爲一個總體顯示時,就須要使用到union或者union all關鍵字。sql
union的做用是將多個結果合併在一塊兒顯示出來。ui
union和uinon all的區別是:union會對結果集中的重複結果去重,而union all則會將全部的結果所有顯示出來。spa
union:對兩個(或多個)結果集進行並集操做,不包括重複行,同時進行默認規則的排序。code
union all:對兩個結果集進行並集操做,包括重複行,不進行排序。排序
能夠在最後一個結果集中指定order by子句改變排序方式。
io
例子以下
class
用戶表t_user以下select
經銷商表t_fchs以下nio
union鏈接兩張表,只顯示兩個字段:名稱和電話號碼im
select * from (select tu.user_name as name,tu.telephone from t_user tu) union (select tf.fchs_name,tf.fchs_telephone from t_fchs tf)
結果以下:
union all鏈接兩張表
select * from (select tu.user_name as name,tu.telephone from t_user tu) union all (select tf.fchs_name,tf.fchs_telephone from t_fchs tf)
結果以下:
由上可知:union是去重了的(去掉了 name:米樂 的那一行),union all所有顯示出來。
2、intersect和minus的用法
Intersect:對兩個結果集進行交集操做,不包括重複行。默認規則排序
例如:對t_user表和t_fchs表求交集
select * from (select tu.user_name as name,tu.telephone from t_user tu) Intersect (select tf.fchs_name,tf.fchs_telephone from t_fchs tf)
結果以下:
備註:由兩張表可知,交集的結果就只有這一個。
3、Minus的用法
Minus:對兩個結果集進行差操做,不包括重複行,同時默認排序
minus的做用是去同留異
select * from (select tu.user_name as name,tu.telephone from t_user tu) minus (select tf.fchs_name,tf.fchs_telephone from t_fchs tf)
結果以下:
備註:t_user與t_fchs的差集操做獲得的結果是
t_user中與t_fchs表中相同的去掉了,不一樣的(只針對t_user表)留下來了。