使用半連接與反連接進行子查詢

在 SQL 中進行資料連接

Maham Faisal Khan

Senior Content Developer, DataCamp

各種連接一次看

id 欄位上的 INNER JOIN 圖示

一張圖說明兩個資料表:left_table 與 right_table。右側顯示連接結果,只回傳兩表在 id 欄位匹配的紀錄。

在 SQL 中進行資料連接

加成式連接(Additive joins)

SELECT *
FROM left_table
INNER JOIN right_table
ON left_table.id = right_table.id;
在 SQL 中進行資料連接

加成式連接(Additive joins)

一張圖解釋加成式連接。左側為兩個資料表 left_table 與 right_table。右側為使用 id 欄位做 INNER JOIN 的結果。不同名稱的欄位以原名加入;由於兩表皆有 date 欄位,結果中會出現兩次。

在 SQL 中進行資料連接

半連接(Semi join)

半連接(semi join) 會選出第一個資料表中,在第二個資料表符合條件的紀錄。

一張圖示兩個資料表 left_table 與 right_table,用於示範半連接。left_table 有兩欄 id 與 col1;right_table 只有一欄 col2。

在 SQL 中進行資料連接

半連接(Semi join)

一張圖示兩個資料表 left_table 與 right_table,用於示範半連接。以 col2 篩選 col1。left_table 中 col1 無法在 col2 找到匹配的紀錄已被淡化。

在 SQL 中進行資料連接

半連接(Semi join)

一張圖示兩個資料表 left_table 與 right_table。右側顯示半連接的結果。只回傳 left_table 中 col1 能在 col2 找到匹配的紀錄,對應的 id 為 2 與 3。

在 SQL 中進行資料連接

開始進行半連接

SELECT country, continent, president
FROM presidents;
| country  | continent     | president               |
| -------- | ------------- | ----------------------- |
| Egypt    | Africa        | Abdel Fattah el-Sisi    |
| Portugal | Europe        | Marcelo Rebelo de Sousa | 
| USA      | North America | Joe Biden               |
| Uruguay  | South America | Luis Lacalle Pou        |
| Pakistan | Asia          | Asif Ali Zardari        |
| Chile    | South America | Gabriel Boric           |
| India    | Asia          | Droupadi Murmu          |
在 SQL 中進行資料連接

擴充我們的半連接

SELECT country
FROM states
WHERE indep_year < 1800;
|----------|
| country  |
|----------|
| Portugal |
| Spain    |
|----------|
在 SQL 中進行資料連接

完成半連接(子查詢入門)

SELECT president, country, continent
FROM presidents
WHERE country IN
    (SELECT country
     FROM states
     WHERE indep_year < 1800);
|-------------------------|-----------|-------------|
| president               | country   | continent   |
|-------------------------|-----------|-------------|
| Marcelo Rebelo de Sousa | Portugal  | Europe      |
|-------------------------|-----------|-------------|
在 SQL 中進行資料連接

反連接(Anti join)

一張圖示兩個資料表 left_table 與 right_table,用於示範反連接。以 col2 篩選 col1。left_table 中 col1 無法在 col2 找到匹配的紀錄「未」被淡化。

在 SQL 中進行資料連接

反連接(Anti join)

一張圖示兩個資料表 left_table 與 right_table。右側顯示反連接的結果。只回傳 left_table 中 col1 無法在 col2 找到匹配的紀錄,對應的 id 為 1 與 4。

在 SQL 中進行資料連接

用總統資料示範反連接

SELECT country, president
FROM presidents
WHERE continent LIKE '%America' 
    AND country NOT IN
        (SELECT country
         FROM states
         WHERE indep_year < 1800);
| country  |  president       |
| -------- | ---------------- | 
| Uruguay  | Luis Lacalle Pou |
| Chile    | Gabriel Boric    |
在 SQL 中進行資料連接

一起來練習吧!

在 SQL 中進行資料連接

Preparing Video For Download...