我似乎无法按照我想要的方式加入这些表格
I can't seem to join these tables the way I want
我在 Oracle 中有两个表,表 1 看起来像这样:
Id_1 | Id_1_Source
23872 | 23870
23873 | 23871
23874 | 23872
23875 | 23872
23876 | 23873
23877 | 23876
23878 | 23877
表 2 如下所示:
Source | Color
23870 | Yellow
23871 | Green
我想显示表1中所有Id_1的颜色,但是
SELECT Table1.Id_1, Table2.Color
FROM Table1, Table2
WHERE Table1.Id_1_Source = Table2.Source
还不够好。问题是 Id_1_Source 有时与表 2 中的源相关,但有时也与表 1 中的另一个 Id_1 相关。 table1 中的另一个 Id_1 也可以与 Table2 中的 Source 相关,但也可以与 table1 中的另一个 Id_1 相关。最终所有 Id_1 id 都可以追溯到 Id_1_Source,它作为源存在于表 2 中,但我不知道如何通过 sql.
获得输出
我想要的结果如下:
Id_1 | Color
23872 | Yellow
23873 | Green
23874 | Yellow
23875 | Yellow
23876 | Green
23877 | Green
23878 | Green
我用 IF ... THEN 或 CASE 尝试了一些东西,但我必须多次这样做,而且所需的次数可能会随着时间的推移而改变,所以我正在寻找另一种解决方案,也许可以利用以某种方式循环。有人可以帮忙吗?
据我了解你的问题,你可以使用递归查询:
with cte (id_1, id_1_source, lvl) as (
select id_1, id_1_source, 1 lvl from table1
union all
select c.id_1, t1.id_1_source, c.lvl + 1
from table1 t1
inner join cte c on t1.id_1 = c.id_1_source
)
select c.id_1, t2.color
from (select c.*, row_number() over(partition by id_1 order by lvl desc) rn from cte c) c
inner join table2 t2 on t2.source = c.id_1_source
where c.rn = 1
想法是使用递归查询为每个 id_1
识别由 table_1
表示的层次结构树中“顶部”记录的 id_1_source
。然后你可以把 table_2
和 join
.
ID_1 | COLOR
----: | :-----
23872 | Yellow
23873 | Green
23874 | Yellow
23875 | Yellow
23876 | Green
23877 | Green
23878 | Green
我在 Oracle 中有两个表,表 1 看起来像这样:
Id_1 | Id_1_Source
23872 | 23870
23873 | 23871
23874 | 23872
23875 | 23872
23876 | 23873
23877 | 23876
23878 | 23877
表 2 如下所示:
Source | Color
23870 | Yellow
23871 | Green
我想显示表1中所有Id_1的颜色,但是
SELECT Table1.Id_1, Table2.Color
FROM Table1, Table2
WHERE Table1.Id_1_Source = Table2.Source
还不够好。问题是 Id_1_Source 有时与表 2 中的源相关,但有时也与表 1 中的另一个 Id_1 相关。 table1 中的另一个 Id_1 也可以与 Table2 中的 Source 相关,但也可以与 table1 中的另一个 Id_1 相关。最终所有 Id_1 id 都可以追溯到 Id_1_Source,它作为源存在于表 2 中,但我不知道如何通过 sql.
获得输出我想要的结果如下:
Id_1 | Color
23872 | Yellow
23873 | Green
23874 | Yellow
23875 | Yellow
23876 | Green
23877 | Green
23878 | Green
我用 IF ... THEN 或 CASE 尝试了一些东西,但我必须多次这样做,而且所需的次数可能会随着时间的推移而改变,所以我正在寻找另一种解决方案,也许可以利用以某种方式循环。有人可以帮忙吗?
据我了解你的问题,你可以使用递归查询:
with cte (id_1, id_1_source, lvl) as (
select id_1, id_1_source, 1 lvl from table1
union all
select c.id_1, t1.id_1_source, c.lvl + 1
from table1 t1
inner join cte c on t1.id_1 = c.id_1_source
)
select c.id_1, t2.color
from (select c.*, row_number() over(partition by id_1 order by lvl desc) rn from cte c) c
inner join table2 t2 on t2.source = c.id_1_source
where c.rn = 1
想法是使用递归查询为每个 id_1
识别由 table_1
表示的层次结构树中“顶部”记录的 id_1_source
。然后你可以把 table_2
和 join
.
ID_1 | COLOR ----: | :----- 23872 | Yellow 23873 | Green 23874 | Yellow 23875 | Yellow 23876 | Green 23877 | Green 23878 | Green