我有以下疑问:
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中的任何解决方案感兴趣。
提前感谢!
发布于 2019-02-22 06:03:00
你似乎想要:
select t1.x, t1.x as y
from table1 t1
union all
select t2.x, t2.y
from table2 t2;
仅当您希望根据两个表中的x
过滤(或相乘)行时,才需要join
。
发布于 2019-02-22 06:05:44
我不确定这是不是你所需要的。但我怀疑您只需要对LEFT JOIN
进行一些调整:
SELECT
t1.x,
COALESCE(t2.y, t1.x)
FROM table1 t1
LEFT JOIN table2 t2
ON t1.x = t2.x
发布于 2019-02-22 05:56:19
您可以使用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
https://stackoverflow.com/questions/54816798
复制相似问题