sql - 在具有父子范围的单个查询中查找所有父项
问题描述
我在 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 的情况下还有另一种方法吗?
解决方案
这只是一个简单的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>
推荐阅读
- java - Java-Springboot SOAP动态客户端
- node.js - 如何从nodejs模块导出函数中获取回调数据
- django - Django:如何为权限创建 ContentType 对象?
- python - 在对数图上设置脊椎位置
- python - 如何使用 python 检测自定义对象?
- corda - 线性状态的 Corda 转移,收集签名
- java - 如何对酒店房间的数组列表进行排序
- cloudkit - 有没有办法从 CloudKit Dashboard 中删除自定义记录类型?
- c++ - v4l2 设备需要在应用重启时重新插入
- java - java.lang.ClassNotFoundException:com.jayway.jsonpath.internal.spi.json.JacksonJsonProvider