SQL合并2个表

时间:2013-02-23 16:27:22

标签: sql join

我是数据库查询编码的新手,我做了一些谷歌,找出如何合并两个表,但INNER JOIN和UNION ALL并不完全符合我的需要。

我有2个完全不同的表格,我希望它能并排在一个

这就是我所拥有的:

+-----------+  +------------+
| ids type  |  | d1  d2  d3 |
+-----------+  +------------+
| 1   01    |  | 45  13  4  |
| 2   02    |  | 46  14  4  |
| 3   03    |  | 47  15  4  |
+-----------+  | 48  16  4  |
               +------------+

我想得到这个:

+-----------------------+
| ids  type  d1  d2  d3 |
+-----------------------+
| 1    01    45  13  4  |
| 2    02    46  14  4  |
| 3    03    47  15  4  |
| NULL NULL  48  16  4  |
+-----------------------+

2 个答案:

答案 0 :(得分:3)

您遇到的问题是您无法加入该表。假设您使用的是合理的数据库,则可以使用row_number()生成一个数据库。我将假设第一个表由ids订购,第二个表由d1订购。

select t1.ids, t1.type, t2.d1, t2.d2, t2.d3
from (select t1.*, row_number() over (order by ids) as seqnum
      from t1
     ) t1 full outer join
     (select t2.*, row_number() over (order by d1) as seqnum
      from t2
     ) t2
     on t1.seqnum = t2.seqnum

这样做是为每个表分配一个序号,然后用于连接。

答案 1 :(得分:0)

以下是使用ROW_NUMBER的几个CTE的一种方式:

with cte1 as (
  select ids, type, ROW_NUMBER() OVER (ORDER BY ids) rn
  from table1 
  ), cte2 as (
  select d1, d2, d3, ROW_NUMBER() OVER (ORDER BY d1) rn
  from table2 
  ) 
select t1.ids, t1.type, t2.d1, t2.d2, t2.d3
from cte1 t1 
  left join cte2 t2 on t1.rn=t2.rn
union 
select t1.ids, t1.type, t2.d1, t2.d2, t2.d3
from cte2 t2 
  left join cte1 t1 on t1.rn=t2.rn
where t1.ids is null

Sample Fiddle Demo