我有一个查询来从Table2中查找子数据,该子数据具有在其他表(即oracle中的TABLE1)中定义的分层数据。
TABLE1
ID, CHILD_ID, PARENT_ID
1, 1
2, 2, 1
3, 3, 2
4, 4, 3
5, 5, 4
6, 6, 4
7, 7, 4
8, 8, 5
9, 9, 5
TABLE2
NAME,AGE,ID
JJ,22,1
XX,19,2
YY,20,3
KK,21,4
PP,18,5
CC,19,6
DD,22,7
SS,44,8
QQ,33,9
当我查询ID 7时,输出应
NAME,AGE,ID
DD,22,7
因为没有7个孩子
当我查询5时,它应该在下面显示为8和9是5的子元素
NAME,AGE,ID
PP,18,5
SS,44,8
QQ,33,9
请提出建议,在此先谢谢
答案 0 :(得分:1)
您可以执行以下操作来处理一般情况(即不仅会得到父母和孩子,而且可能会得到孩子的孩子,依此类推)。
with thevalues as
(
SELECT child, parent
FROM table1
START WITH parent=4
CONNECT BY PRIOR child = parent
)
SELECT *
FROM table2
WHERE id IN (SELECT child FROM thevalues UNION ALL SELECT parent FROM thevalues)
其中parent=4
定义起始记录。 Connect By用于此类分层查询。
尽管上面的示例也适用于简单的情况,但如果您不关心子代子女,则可能更喜欢
SELECT *
FROM table2
WHERE id=4
UNION ALL
SELECT *
FROM table2
WHERE id IN
(
SELECT child
FROM table1
WHERE parent=4
)
请注意,在此示例中,我已经在两个地方对4进行了硬编码。
答案 1 :(得分:1)
如果只需要直系子代,则exists
子查询就足够了:
select t2.*
from table2 t2
where exists (
select 1 from table1 t1 where t1.child_id = t2.id and 5 in (t1.child_id, t1.parent_id)
)
或者:
select t2.*
from table2 t2
where t2.id = 5 or exists (
select 1 from table1 t1 where t1.child_id = t2.id and t1.parent_id = 5
)
另一方面,如果您希望所有子级,无论其级别如何,那么我建议您进行递归查询:
with cte (child_id, parent_id) as (
select child_id, parent_id from table1 where child_id = 5
union all
select t1.child_id, t1.parent_id
from cte c
inner join table1 t1 on t1.parent_id = c.child_id
)
select t2.*
from table2 t2
where exists (select 1 from cte c where c.child_id = t2.id)
答案 2 :(得分:0)
您可以使用类似这样的查询来找到合适的孩子。只需将您在CONNECT_BY_ROOT (t1.id) = 5
子句中搜索的ID从5更改为任何ID,即可正常使用。
SELECT t2.name, t2.age, t1.id
FROM table1 t1, table2 t2
WHERE t1.id = t2.id AND CONNECT_BY_ROOT (t1.id) = 5
CONNECT BY PRIOR t1.id = t1.parent_id;