简体   繁体   English

如何在同一列中包含两个表中的值

[英]How to include the values from two tables in the same column

I have the following query: 我有以下查询:

select
    t1.x,
    t2.y

from table1 t1
    join table2 t2
        on t1.x = t2.x

which is producing the following results: 产生以下结果:

x   y1
x   y2
x   y3

I, however, want it to produce the following, where the value from t1.x is also in the second column: 但是,我希望它产生以下内容,其中t1.x中的值也在第二列中:

x   x
x   y1
x   y2
x   y3

Is there an easy way to do this? 是否有捷径可寻? I'm trying to achieve this in PostgreSQL but I would also be interested in any solution in MySQL. 我正在尝试在PostgreSQL中实现这一目标,但我也对MySQL中的任何解决方案感兴趣。

Thanks in advance! 提前致谢!

You seem to want: 您似乎想要:

select t1.x, t1.x as y
from table1 t1
union all
select t2.x, t2.y
from table2 t2;

The join is only needed if you want to filter (or multiply) the rows, based on x being in both tables. 仅当您要基于两个表中的x来过滤(或相乘)行时才需要join

I am not sure if that is what you need. 我不确定这是否是您所需要的。 But I suspect you just need LEFT JOIN with some tweak: 但是我怀疑您只需要通过一些调整就可以LEFT JOIN

SELECT
    t1.x,
    COALESCE(t2.y, t1.x)
FROM table1 t1
LEFT JOIN table2 t2
ON t1.x = t2.x

You can use UNION: 您可以使用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

or 要么

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM