【问题标题】:I can't seem to join these tables the way I want我似乎无法按照我想要的方式加入这些表格
【发布时间】:2021-02-03 06:50:09
【问题描述】:

我在 Oracle 中有两个表,Table1 看起来像这样:

Id_1 |  Id_1_Source  
23872 | 23870  
23873 | 23871  
23874 | 23872  
23875 | 23872  
23876 | 23873  
23877 | 23876  
23878 | 23877

Table2 如下所示:

Source | Color  
23870 | Yellow  
23871 | Green

我想要的是在 Table1 中显示所有 Id_1 的颜色,但是

SELECT Table1.Id_1, Table2.Color
FROM Table1, Table2
WHERE Table1.Id_1_Source = Table2.Source  

还不够好。问题是 Id_1_Source 有时与 Table2 中的 Source 相关,但有时也与 table1 中的另一个 Id_1 相关。 table1 中的另一个 Id_1 也可以与 Table2 中的 Source 相关,但也可以与 table1 中的另一个 Id_1 相关。最终,所有 Id_1 id 都可以追溯到作为 Source 存在于 Table2 中的 Id_1_Source,但我不知道如何通过 sql 获取该输出。

我想要的结果如下:

Id_1 | Color  
23872 | Yellow  
23873 | Green  
23874 | Yellow  
23875 | Yellow  
23876 | Green  
23877 | Green  
23878 | Green

我尝试了 IF ... THEN 或 CASE,但我必须多次这样做,并且所需的次数可能会随着时间而改变,所以我正在寻找另一种解决方案,也许使用 LOOP不知何故。有人可以帮忙吗?

【问题讨论】:

  • 今日提示:切换到现代、明确的JOIN 语法!更容易编写(没有错误),更容易阅读和维护,如果需要更容易转换为外连接!
  • 使用递归 cte。

标签: sql oracle inner-join hierarchical-data recursive-query


【解决方案1】:

据我了解您的问题,您可以使用递归查询:

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_source,每个id_1table_1 表示。然后你可以带上table_2join

Demo on DB Fiddle

ID_1 |颜色 ----: | :----- 23872 |黄色的 23873 |绿色的 23874 |黄色的 23875 |黄色的 23876 |绿色的 23877 |绿色的 23878 |绿色的

【讨论】:

  • 我必须再读几遍你的答案才能理解你写的东西,但它是 100% 有效的!!非常感谢!
猜你喜欢
  • 2014-07-18
  • 1970-01-01
  • 1970-01-01
  • 2021-01-19
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
相关资源
最近更新 更多