我需要從不同表中具有相同名稱的 2 列中獲取每個值。所有這些都帶有來自另一列的匹配條件
//TABLE1
city | code |
here | 123 |
there | 567 |
another| 498 |
//TABLE2
city | code |
here | 813 |
there | 379 |
another| 111 |
城市“那里”的預期結果
| 567 |
| 379 |
我用 JOIN 和 UNION 嘗試了很多可能性,但我能找到正確的方法
uj5u.com熱心網友回復:
你需要垂直連接表,你可以使用 UNION
SELECT code FROM table1 WHERE city = 'there'
UNION
SELECT code FROM table2 WHERE city = 'there'
如果你有超過少量的禁忌,你需要用 cahe 或 if 子句聚合
uj5u.com熱心網友回復:
我建議你這兩個請求,你可以在這個鏈接中看到結果:http : //sqlfiddle.com/#!9/ded8d6/9
(SELECT code FROM TABLE1 WHERE city = 'there')
UNION
(SELECT code FROM TABLE2 WHERE city = 'there');
SELECT code FROM
(
(SELECT * FROM TABLE1)
UNION
(SELECT * FROM TABLE2)
) T
WHERE T.city = 'there';
uj5u.com熱心網友回復:
我想建議使用以下查詢中的任何人,您可以在此鏈接中看到結果:[http://sqlfiddle.com/#!9/ded8d6/13][1]
1.
SELECT code FROM table1 WHERE city = 'there'
UNION
SELECT code FROM table2 WHERE city = 'there'
2.
SELECT code FROM table1 WHERE city = 'there'
UNION ALL
SELECT code FROM table2 WHERE city = 'there'
Union 和 Union All 之間的唯一區別是 Union 提取查詢中指定的行,而 Union All 提取所有行,包括兩個查詢中的重復(重復值)。
uj5u.com熱心網友回復:
如果為城市設定變數,則不需要在聯合查詢中對其進行兩次硬編碼。
set @city = 'there'; select code from TABLE1 where city = @city union select code from TABLE2 where city = @city order by code
| 代碼 |
|---|
| 379 |
| 567 |
關于db<>fiddle 的演示在這里
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/386897.html
上一篇:復雜結構所需的SQL查詢
