2

我是数据库查询编码的新手,我做了一些谷歌来了解如何将两个表合并为一个,但 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  |
+-----------------------+
4

2 回答 2

3

您遇到的问题是您没有 ke 可以加入表格。假设您使用的是合理的数据库,您可以使用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

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

于 2013-02-23T16:36:21.873 回答
0

这是使用几个 CTE 的一种方法ROW_NUMBER

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

小提琴演示示例

于 2013-02-23T16:40:05.973 回答