mysql集合運算教程 SQL之集合運算

2021-10-19 19:54:16 字數 2243 閱讀 6204

union(並集)集合運算

1.union all集合運算

該集合運算返回在輸入的多集**現的所有行,它實際上不會對行進行比較,也不會刪除重複行。假設查詢query1返回m行,查詢query2返回n行,則該集合運算後返回(m+n)行

1 select country, region, city fromhr.employees2 union all

3 select country, region, city from sales.customers;

2.union distinct集合運算

此集合運算如果兩個輸入集中包含相同的行,則該行在結果中只出現一次,也就是說運算結果是乙個真正的集合,而不是多集

1 select country, region, city fromhr.employees2 union

3 select country, region, city from sales.customers;

intersect(交集)集合運算

1.intersect distinct集合運算

1 select country, region, city fromhr.employees2 intersect

3 select country, region, city from sales.customers;

2.intersect all集合運算

sql server不支援內建的intersect all運算,那麼我們需要另外的解決方案來實現此集合運算。首先先看一段**

1 select

2 row_number()3 over(partition bycountry, region, city4 order by (select 0)) asrownum,5 country, region, city6 from hr.employees

執行結果:

row_number函式是關鍵,它能給我們提供行號;另外,上面的sql中order by後面的select 0是表示查詢可以不必在意行的順序,即不對資料進行排序。分析該查詢結果可知,intersect all的完整解決方案是:

1 select

2 row_number()3 over(partition bycountry, region, city4 order by (select 0)) asrownum,5 country, region, city6 fromhr.employees7

8 intersect

10 select

11 row_number()12 over(partition bycountry, region, city13 order by (select 0)),14 country, region, city15 from sales.customers;

except(差集)集合運算

注意,集合a與b的差集(a-b)是由屬於集合a,但不屬於集合b的元素組成的集合,也就是兩集和之差a-b是從a中減去b中也屬於a的元素,故差集運算是不對稱的,a-b和b-a是不一樣的。

1.except distinct集合運算

1 select country, region, city fromhr.employees2 except

3 select country, region, city from sales.customers;

2.except all集合運算

sql server沒有提供內建的此集合運算。解決方案如下:

1 withexcept_all2 as

3 (4 select

5 row_number()6 over(partition bycountry, region, city7 order by (select 0)) asrownum,8 country, region, city9 fromhr.employees10

11 except

13 select

14 row_number()15 over(partition bycountry, region, city16 order by (select 0)),17 country, region, city18 fromsales.customers19 )20 selectcountry, region, city21 from except_all;

集合運算的優先順序:intersect比union和except運算的優先順序高,union和except優先順序相等。

SQL集合運算

集合運算是對輸入的兩個或多個集合進行的運算,最終輸出乙個結果集。t sql支援3種集合運算 並集 union 交集 intersect 和差集 except 集合運算的基本格式為 輸入的集合1 集合運算 輸入的集合2 order by 需要注意的是,集合運算涉及的兩個查詢不能包含order by 子...

SQL集合運算

1.表的加減法 1 定義 集合在數學領域表示 各種各樣的事物的總和 在資料庫領域表示記錄的集合.具體來說,表 檢視和查詢的執行結果都是記錄的集合,其中的元素為表或者查詢結果中的每一行。在標準 sql 中,分別對檢索結果使用union,intersect,except來將檢索結果進行並,交和差運算,像...

SQL集合運算

本系列 t sql基礎 主要是針對t sql基礎的總結。t sql基礎 01.單錶查詢 幾道sql查詢題 t sql基礎 02.聯接查詢 t sql基礎 03.子查詢 t sql基礎 04.表表示式 上篇 t sql基礎 04.表表示式 下篇 t sql基礎 05.集合運算 本系列 t sql基礎 ...