首页 > 解决方案 > 如何将两个表中的值包含在同一列中

问题描述

我有以下查询:

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 中的任何解决方案感兴趣。

提前致谢!

标签: mysqlsqlpostgresql

解决方案


你似乎想要:

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

仅当join您想要基于x在两个表中的行来过滤(或相乘)行时才需要。


推荐阅读