如果有人可以提供帮助,我会很感激。 我有两张没有关系的桌子:
TABLE_1
ID NAME VALUE
1 abc 10
2 def 20
3 def 20
TABLE_2
ID2 NAME2 VALUE2
5 ghi 30
6 gkl 40
我想要一个select语句,它将显示来自两个表的数据:
ID NAME VALUE ID2 NAME2 VALUE2
1 abc 10 5 ghi 30
2 def 20 6 gkl 40
3 def 20
重点是在一行中显示每条记录的数据,表格如下:
ID NAME VALUE ID2 NAME2 VALUE2
5 ghi 30
6 gkl 40
如果Table_1
没有记录。 Table_2
也是如此。
我尝试使用交叉连接,但随后数据将重复。
非常感谢
答案 0 :(得分:3)
您需要添加join
条件。在这种情况下,通过使用row_number()
在每一侧添加序号。然后full outer join
获取所有记录:
select t1.id, t1.name, t1.value, t2.id as id2, t2.name as name2, t2.value as value2
from (select t1.*, row_number() over (order by id) as seqnum
from table_1 t1
) t1 full outer join
(select t2.*, row_number() over (order by id) as seqnum
from table_2 t2
) t2
on t1.seqnum = t2.seqnum;
答案 1 :(得分:1)
试试这个:
with Table_1(ID, NAME, VALUE) as (
select 1, 'abc', 10 union all
select 2, 'def', 20 union all
select 3, 'def', 20
), Table_2(ID2, NAME2, VALUE2) as (
select 5, 'ghi', 30 union all
select 6, 'gkl', 40
), prep_table_1 (ID, NAME, VALUE, rn) as (
select id, name, value, row_number() over(order by id)
from table_1
), prep_table_2 (ID2, NAME2, VALUE2, rn) as (
select id2, name2, value2, row_number() over(order by id2)
from table_2
)
select t1.ID, t1.NAME, t1.VALUE, t2.ID2, t2.NAME2, t2.VALUE2
from prep_table_1 t1
full outer join prep_table_2 t2 on t1.rn = t2.rn
答案 2 :(得分:0)
这也有效
从Table_1,Table_2中选择*