[英]SQL Server: How to get all child records given a parent id in a self referencing table
[英]Query to get child records of given parent id
我有一个查询来查找 Table2 中的子数据,这些子数据具有在其他表中定义的分层数据,即 oracle 中的 TABLE1。
表格1
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
表2
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
请建议,提前致谢
您可以执行以下操作来处理一般情况(即不仅会得到父母和孩子,还会得到潜在的孩子的孩子等等)。
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。
如果你只想要直接的孩子,那么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)
您可以使用这样的查询来查找合适的子项。 只需将您在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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.