PostgreSQL中UNION和UNION ALL
在SQL中,UNION和UNION ALL運算子可以用來幫助我們獲取多個表,並將結果放入一個表中,其中包含所有匹配的列。如果希望結果作為單個記錄集返回,則使用此運算子會非常有幫助。
何時應該使用Union?
當多個表具有相同的結構但由於某種原因(通常出於效能考慮或存檔目的)而被拆分時,通常需要使用UNION運算子。
而且,有以下幾個注意事項:
1.所有單個查詢必須具有相同數量的列和相容的資料型別。
2.不匹配的查詢將無法執行。
3.在構建查詢時驗證一致性。
4.預設情況下,UNION僅返回不同的值。
舉個例子:
有兩張表,內容分別是學生和教授的相關資訊。如下所示:
postgres=# select * from students; id | name | major ----+-------+------------------- 1 | Wang | Computer Science 2 | Tang | Civil Engineering 3 | Zhang | English (3 rows) postgres=# select * from professors; id | name | major ----+-------+---------- 1 | Zheng | Japanese 2 | Hao | Music (2 rows)
要將這兩個表合併在一起,需要執行此查詢:
postgres=# select * from students union select * from professors;
id | name | major
----+-------+-------------------
1 | Zheng | Japanese
3 | Zhang | English
1 | Wang | Computer Science
2 | Tang | Civil Engineering
2 | Hao | Music
(5 rows)
注意:一旦此查詢執行,資料將不會以任何特定順序顯示。當然,可以使用ORDER BY來確保資料正確排序。
何時應該使用UNION ALL?
前面提到,UNION運算子預設只返回不同的值。 如果希望結果包含所有值,即包括重複值,那麼可以使用UNION ALL。
但是,UNION ALL也不保證生成的行將按任何特定順序排列。因此,就像使用UNION一樣,可以使用ORDER BY進行排序。
舉個例子,有如下兩張表::
postgres=# select * from club;
name | country
----------+---------
Bayern | Germany
Dortmund | Germany
Bremen | Germany
(3 rows)
postgres=# select * from champion;
name | country
-----------+---------
Chelsea | England
Barcelona | Spain
Bayern | Germany
(3 rows)
如果只是執行UNION,那麼結果會如下所示:
postgres=# select * from club union select * from champion;
name | country
-----------+---------
Bayern | Germany
Bremen | Germany
Chelsea | England
Dortmund | Germany
Barcelona | Spain
(5 rows)
但是這樣就會失去一條重複的記錄。如果想要顯示全部的記錄,包括重複的部分,那麼應該用UNION ALL替換UNION。
postgres=# select * from club union all select * from champion;
name | country
-----------+---------
Bayern | Germany
Dortmund | Germany
Bremen | Germany
Chelsea | England
Barcelona | Spain
Bayern | Germany
(6 rows)
現在結果中就會顯示兩張表中的所有記錄。
注意:UNION ALL可以更快地執行,因為它不必過濾掉重複項。
UNION和UNION ALL是統一多個查詢結果的好方法。可以使用UNION檢視整個不同記錄的集合,而且也可以使用UNION ALL檢視包含重複記錄的完整集。必要的時候可以使用ORDER BY來確保結果按照您想要的順序進行顯示。
By kalath