[英]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.