首页 > 解决方案 > 在具有父子范围的单个查询中查找所有父项

问题描述

我在 DB2 中有下表,其中包含父范围和子范围。每行包含父项及其子项可以具有的相应最小值和最大值:

    parent         child_min   child_max
    ------         ---------   ----------
      1              100           300
      2              500           899
     ...
     ...

现在,我试图在一个查询中找到一组孩子的父母。

示例:我有子 ID:

    101, 102, 105, 208, 506.

现在查询应该返回他们各自的父母

    1,1,1,1,2.

我是通过 CTE 做到的。

    WITH temp(id) AS (VALUES
    101,102,105,208,506)
    SELECT parent FROM table,temp 
    WHERE child_min < = temp.id
    AND child_max >= temp.id

但是在单个查询中没有 CTE 的情况下还有另一种方法吗?

标签: sqldb2parent-child

解决方案


这只是一个简单的JOIN. 考虑以下数据(我添加了一个额外的行):

create table parent_children (
  parent int,
  child_min int,
  child_max int
);

insert into parent_children (parent, child_min, child_max) values (1, 100, 300);
insert into parent_children (parent, child_min, child_max) values (2, 500, 899);

查询将是:

with children (id) as (values 101, 102, 105, 208, 506, 1000)
select c.id, p.parent
  from children c
  left join parent_children p on c.id between p.child_min and p.child_max;

结果:

ID          PARENT       
----------  -------
101         1            
102         1            
105         1            
208         1            
506         2            
1000        <null>   

推荐阅读