[英]How to include the values from two tables in the same column
我有以下查詢:
select
t1.x,
t2.y
from table1 t1
join table2 t2
on t1.x = t2.x
產生以下結果:
x y1
x y2
x y3
但是,我希望它產生以下內容,其中t1.x中的值也在第二列中:
x x
x y1
x y2
x y3
是否有捷徑可尋? 我正在嘗試在PostgreSQL中實現這一目標,但我也對MySQL中的任何解決方案感興趣。
提前致謝!
您似乎想要:
select t1.x, t1.x as y
from table1 t1
union all
select t2.x, t2.y
from table2 t2;
僅當您要基於兩個表中的x
來過濾(或相乘)行時才需要join
。
我不確定這是否是您所需要的。 但是我懷疑您只需要通過一些調整就可以LEFT JOIN
:
SELECT
t1.x,
COALESCE(t2.y, t1.x)
FROM table1 t1
LEFT JOIN table2 t2
ON t1.x = t2.x
您可以使用UNION:
select
x,
x as y
from table1
union
select
t1.x,
t2.y
from table1 t1
join table2 t2
on t1.x = t2.x
order by x
要么
select
t1.x,
t1.x
from table1 t1
join table2 t2
on t1.x = t2.x
union
select
t1.x,
t2.y
from table1 t1
join table2 t2
on t1.x = t2.x
order by x
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.