我正在尝试将双表连接到另外两个包含具有相同键的数据的表
这是结构;
我的第一栏就像:
(with bnd as (select 1 lo, 100 hi from dual)
select (select lo from bnd) - 1 + level r
from dual
这将导致整数范围
Id r
1| 1
2| 2
3| 3
4| 4
然后我想加入两个表,其中每行包含1到100之间的数字(每个数字只能存在于其中一个中)
A
Id r Type
1| 1 Cat
2| 3 Dog
3| 9 Cat
乙
Id r Type
1| 2 Woman
2| 6 Man
3| 8 Woman
最终结果应显示“r”和2个表中的Type,如果找不到r,则返回null(按升序排序):
Id r Type
1|1 Cat
2|2 Woman
3|3 Dog
4|4 Null
有什么想法吗?我一直在使用Management Studio,所以我没有任何经验,请提前感谢任何提示。
答案 0 :(得分:1)
生成数字的更典型方法是:
with bounds as (
select 1 as lo, 4 as hi from dual
),
n as (
select level + lo - 1 as lvl
from bounds
connect by level + lo - 1 <= hi
)
select *
from n;
然后,为了做你想做的事,你可以使用left joins
:
with bounds as (
select 1 as lo, 4 as hi from dual
),
n as (
select level + lo - 1 as r
from bounds
connect by level + lo - 1 <= hi
)
select n.r, coalesce(a.type, b.type)
from n left join
a
on n.t = a.r left join
b
on n.r = b.r