iT邦幫忙

2024 iThome 鐵人賽

DAY 7
0

集合

每一段SQL查詢結果都可被視為一個集合, 透過集合運算子進行資料集運算。集合邏輯可以搭配下方文氏圖理解:聯集代表A或者B的集合、交集代表是A也是B差集代表是A但不是B
https://ithelp.ithome.com.tw/upload/images/20240818/201623022HOHHtTi2p.png

集合運算子

Example使用的table

with Travel as (
    select 'Amy' name, 'Japan' country
    union all
    select 'Oleve' name, 'Denmark' country
    union all
    select 'Jake' name, 'France' country
    union all
    select 'Luisa' name, 'Greece' country
    union all
    select 'Freddy' name, 'Japan' country
), Student as (
    select 'Amy' name, 123456 ID
    union all
    select 'Oleve' name, 567899 ID
    union all
    select 'Jake' name, 586966 ID
)
  • UNION / UNION ALL:聯集, 兩個查詢結果出現

    1. union all 含重複項目
    select name from Travel t
    union all
    select name from Student t
    ;
    -- output
    Amy
    Oleve
    Jake
    Luisa
    Freddy
    Amy -- 第2次出現
    Oleve -- 第2次出現
    Jake -- 第2次出現
    
    1. union 不含重複項目(類似加入distinct)
    select name from Travel t
    union
    select name from Student t
    ;
    -- output
    Amy
    Oleve
    Jake
    Luisa
    Freddy
    
  • Intersect:交集, 兩個查詢結果只出現重複項目

select name from Travel t
intersect
select name from Student t
;
-- output
Amy
Oleve
Jake
  • Minus / Except:差集, 查詢結果1扣除查詢結果2 (即是查詢結果1, 但非查詢結果2)
-- 查詢結果1
select name from Travel t
minus -- 替換成 except 結果相同, 但要看版次是否支援此語法
-- 查詢結果2
select name from Student t
;
-- output
Luisa
Freddy

Reference


上一篇
Day 6 基礎-從子查詢到WITH子句
下一篇
Day 8 基礎-邏輯運算子
系列文
不居功的系統隱士 - 30天由淺入深學SQL14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言