将两张桌子合为一体?

问题描述 投票:1回答:1

我的问题很简单,我只想将两个表合并为一个表而无需任何PK第一个表是完全不同的,他们没有什么不同

table1.            table2.
|в|q|              |@|John |
|ы|a|              |£|Sara |
|в|f|              |$|ciro |
|с|g|              |%|Jo.  |
|ф|s|

我需要的是

Table3
|в|q|@|John |
|ы|a|£|Sara |
|в|f|$|ciro |
|с|g|%|Jo.  |
|ф|s|-|-    |


mysql sql mysql-workbench jointable
1个回答
0
投票

这有点复杂。您需要一个“垂直”列表,但没有匹配的列。您可以使用row_number()union all

select max(t1_col1), max(t1_col2), max(t2_col1), max(t2_col2)
from ((select t1.col1 as t1_col1, t1.col2 as t1_col2,
              null as t2_col1, null as t2_col2, row_number() over () as seqnum
       from table1 t1
      ) union all
      (select null, null, t2.col1, t2.col2, row_number() over () as seqnum
       from table2 t2
      ) 
     ) t
group by seqnum;

Here是db <>小提琴。

请注意,这将保留两个表中的所有行,无论哪个行较长。每列中各行的具体顺序不确定。 SQL表表示无序集。如果您想要按特定顺序排列商品,则需要一列来指定顺序。

如果要保存到新表中,请在create table as table3之前放置select。如果要插入到现有表中,请使用insert

© www.soinside.com 2019 - 2024. All rights reserved.