【问题标题】:Finding all parents in a single query with parent and child ranges在具有父子范围的单个查询中查找所有父项
【发布时间】:2018-08-09 16:50:38
【问题描述】:

我在 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 的情况下还有另一种方法吗?

【问题讨论】:

  • 您的查询单个查询。碰巧使用了CTE,但这是非常合理的。
  • 同意。公用表表达式 (CTE) 不是“临时表”。
  • 嗯,我的架构设计有问题:您的孩子范围似乎指定了孩子可以拥有的最小/最大 id,这将产生可怕的影响关于设计(一方面,该表上没有自动生成 ID)。 通常,父/子关系是通过存储自引用来完成的(即,每个子都存储其父)。另外,你的上限是包容性的,这让我很恼火(但不是太大的问题)

标签: sql db2 parent-child


【解决方案1】:

这只是一个简单的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>   

【讨论】:

  • 我试图避免 CTE。没有CTE可以吗?
  • 是的,CTE 仅用于演示目的。如果您在另一个表中有子 ID,则可以改用那个。
【解决方案2】:

你喜欢这个吗?

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 2021-04-12
    相关资源
    最近更新 更多