請幫助修改以下代碼。我想加入這兩個選擇查詢,以便我可以從兩個差異表中獲得包含記錄的單個輸出?我有4張桌子,
table_a 有我必須用來搜索的用戶 ID
table_b1 具有 table_c 的外鍵,它具有我想要獲取的名稱
table_b2 也有 table_c 的外鍵,它也有我想要的第二個名字。
如何在單個輸出中組合以下查詢?
我的代碼
select c.name from table_a a
join table_b1 b1 on a.id=b1.id
join table_c c on b1.pri_id=c.id where a.user='abc'
select c.name from table_a a
join table_b2 b2 on a.id=b2.id
join table_c c on b2.pri_id=c.id where a.user='abc'
uj5u.com熱心網友回復:
也許你可以像這樣在這里使用 UnionAll,
select c.name from table_a a
join table_b1 b1 on a.id=b1.id
join table_c c on b1.pri_id=c.id where a.user='abc'
union all
select c.name from table_a a
join table_b2 b2 on a.id=b2.id
join table_c c on b2.pri_id=c.id where a.user='abc'
uj5u.com熱心網友回復:
因此,您要提取 table_c 中表 table_b1 和 table_b2 的名稱資訊,它們也通過 id 列連接到 table_a。您需要將 table_c 添加到查詢中兩次以從 table_b1 中檢索名稱和從 table_b2 中檢索名稱,因為檢索名稱的條件不同。
如果您只需要在 table_b1 AND table_b2 中有資訊(以及每個 b 表的 table_c 中)有資訊的情況下,查詢將是:
SELECT tc1.name name_b1, tc2.name name_b2
FROM table_a ta
JOIN table_b1 tb1 ON ta.id = tb1.id
JOIN table_b2 tb2 ON ta.id = tb2.id
JOIN table_c tc1 ON tb1.pri_id = tc1.id
JOIN table_c tc2 ON tb2.pri_id = tc2.id
WHERE ta.user = 'abc'
如果在 table_b1 或 table_b2 中可能并不總是有用戶資訊,但您仍然想檢索資訊,當一個或兩個 b 表上沒有名稱時獲取 NULL,您將需要左連接:
SELECT tc1.name name_b1, tc2.name name_b2
FROM table_a ta
LEFT JOIN table_b1 tb1 ON ta.id = tb1.id
LEFT JOIN table_b2 tb2 ON ta.id = tb2.id
LEFT JOIN table_c tc1 ON tb1.pri_id = tc1.id
LEFT JOIN table_c tc2 ON tb2.pri_id = tc2.id
WHERE ta.user = 'abc'
uj5u.com熱心網友回復:
像這樣的東西?
select c.name from table_a a
join table_b1 b1 on a.id=b1.id
join table_c c on b1.pri_id=c.id where a.user='abc'
join table_b2 b2 on a.id=b2.id
join table_c c2 on b2.pri_id=c2.id
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/448721.html
上一篇:ORA-14300:磁區鍵映射到超出最大允許磁區數的磁區
下一篇:批量放入表物件
