集合運算子

Oracle SQL 入門

Sara Billen

Curriculum Manager

什麼是集合運算子?

$$

集合運算子會將兩個或多個 SELECT 查詢的輸出合併為一個結果。

$$

  • Join 子句合併資料表
    • 以欄為主
  • 集合運算子合併查詢
    • 以列為主
Oracle SQL 入門

集合運算子的種類

Union

Union operator

所有列(去除重複)

Union All

Union all operator

所有列(保留重複)

Intersect

Intersect operator

兩個查詢共同輸出的列

Minus

Minus operator

第 1 個查詢中不在第 2 個查詢的獨特列

Oracle SQL 入門

Union

所有列(去除重複)

有哪些城市與我們的客戶相關?

SELECT City FROM Customer
UNION
SELECT BillingCity FROM Invoice
| City           |
|----------------|
| Lyon           |
| Fort Worth     |
| Vienne         |
| Brussels       |
| Orlando        |
| Copenhagen     |
| Oslo           |
| Rio de Janeiro |
| Boston         |
| ...            |
Oracle SQL 入門

Union all

所有列(保留重複)

有哪些城市與我們的客戶相關?各自出現頻率?

SELECT City from Customer
UNION ALL
SELECT BillingCity from Invoice
| City          |
|---------------|
| Oslo          |
| Prague        |
| Prague        |
| Vienee        |
| Brussels      |
| Copenhagen    |
| Mountain View |
| Mountain View |
| Mountain View |
| ...           |
Oracle SQL 入門

Intersect

兩個查詢共同輸出的列

哪些 Miles Davis 的曲目在播放清單中?

(SELECT TrackId from PlaylistTrack)
INTERSECT
(SELECT TrackId from Track
WHERE Composer = 'Miles Davis')
| TrackId |
|---------|
| 612     |
| 600     |
| 614     |
| 604     |
| 605     |
| 598     |
| 617     |
Oracle SQL 入門

Minus

第 1 個查詢中不在第 2 個查詢的獨特列

哪些藝人不作曲?

(SELECT Name FROM Artist)
MINUS
(SELECT Composer FROM Track)
ORDER BY 1 DESC
| Name                     |
|--------------------------|
| Zeca Pagodinho           |
| Youssou N'Dour           |
| Yo-Yo Ma                 |
| Yehudi Menuhin           |
| Xis                      |
| Wilhelm Kempff           |
| Whitesnake               |
| Vinícius E Qurteto Em Cy |
| Vinícius E Odette Lara   |
| ...                      |                                                                       |
Oracle SQL 入門

一起來練習吧!

Oracle SQL 入門

Preparing Video For Download...