簡體   English   中英

即使主鍵和外鍵不均勻,SQL 查詢也能從多個表中獲取所有行

[英]SQL query to get all the rows from multiple tables even it has uneven primary and foreign keys

我有多個表,如下所示

表格1:

    ID | Name
----------------
     1 | John
     2 | Doe
     3 | Mark
     4 | Hill
     5 | Ram

表 2:

    ID | place
----------------
     1 | CA
     2 | NY
     4 | AK
     5 | CT

表3:

    ID | age
----------------
     2 | 35
     3 | 23
     4 | 54

我需要將輸出表作為

表格1:

    ID | Name   | Place   |  Age
-----------------------------------
     1 | John   | CA     | 
     2 | Doe    | NY     |  35
     3 | Mark   |        |  23 
     4 | Hill   | AK     |  54
     5 | Ram    | CT     |  

我嘗試使用joinunion ,但是我找不到解決方案。 你能請人給我解決方案嗎?

您需要使用 join 如下:

select t1.id, t1.name,t2.place, t3.age
from table1 t1 join table2 t2 on t1.id = t2.id
left join table3 t3 on t1.id = t3.id

可以使用外連接獲得如圖所示的結果:

select *
from table1 
  left join table2 using (id)
  left join table3 using (id);

通過using運算符的連接有一個很好的副作用,即使我使用了select * ,ID 列也只會在結果中出現一次

您的示例沒有顯示這一點,但如果您在 table2 中有不在table1 中的 ID,但您仍然希望它們出現在結果中,則需要使用完整的外部聯接。

select *
from table1 
  full join table2 using (id)
  full join table3 using (id);

using (id) know 有另一個很好的副作用:它會自動使用 id 來自哪個表的 ID 值,而無需在選擇列表中使用coalesce(id)

選擇 t1.id、姓名、地點、年齡

從表 1 t1

` t1.id=t2.id 上的左外連接 table2

   left outer join table3 on t1.id=t3.id;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM