SQL嵌套查询

时间:2011-04-19 04:21:48

标签: sql

我有一张如下表格

id  name     dependency
-----------------------
1   xxxx     0
2   yyyy     1
3   zzzz     2 
4   aaaaaa   0
5   bbbbbb   4
6   cccccc   5

列表还在继续。我想从这个表中选择一组行,在SQL的where子句中给出0依赖的名称,直到它达到不再依赖的条件。 (例如,行1,2,3形成一个组,行4,5,6是另一组)。请帮助

5 个答案:

答案 0 :(得分:1)

由于您没有指定产品,我将使用SQL规范中提供的功能。在这种情况下,我使用的是一个公用表表达式,它受到许多数据库产品的支持,包括SQL Server 2005+和Oracle(但不是MySQL):

With MyDependents As
    (
    Select id, name, 0 As level
    From MyTable
    Where dependency = 0
        And name = 'some value'
    Union All
    Select T.id, T.name, T.Level + 1
    From MyDependents As D
        Join MyTable As T
            On T.id = D.dependency
    )
Select id, name, level
From MyDependents

另一个不依赖于公用表表达式但确实假设最大深度级别(在这种情况下是低于0级的两个级别)的解决方案就像是

Select T1.id, T1.name, 0 As level
From MyTable As T1
Where T1.name = 'some value'
Union All
Select T2.id, T2.name, 1 
From MyTable As T1
    Join MyTable As T2
        On T2.Id = T1.Dependency
Where T1.name = 'some value'
Union All
Select T3.id, T3.name, 2
From MyTable As T1
    Join MyTable As T2
        On T2.Id = T1.Dependency
    Join MyTable As T3
        On T3.Id = T2.Dependency
Where T1.name = 'some value'

答案 1 :(得分:0)

听起来你想要递归地查询你的表,你需要一个公用表表达式(CTE)

This MSDN article很好地解释了CTE。它们起初令人困惑,但却非常容易实现。

BTW这显然只适用于SQL Server,我不确定你是如何在MySQL中实现的。

答案 2 :(得分:0)

这是我想到的第一件事。它可以更直接/更简洁地完成,我会试着再详述一下。

SELECT *
FROM table T1
WHERE T1.id >= 
         (SELECT T2.id FROM table T2 WHERE T2.name = '---NAME HERE---')
      AND T1.id <
        (SELECT MIN(id)
        FROM table T3
        WHERE T3.dependency = 0 AND T3.id > T2.id)

答案 3 :(得分:0)

如果你可以估计一个最大深度,这可以解决:

SELECT 
   COALESCE(t4.field1, t3.field1, t2.field1, t1.field1, t.field1),
   COALESCE(t4.field2, t3.field2, t2.field2, t1.field2, t.field2),
   COALESCE(t4.field3, t3.field3, t2.field3, t1.field3, t.field3),
....
FROM table AS t
LEFT JOIN table AS t1 ON t.dependency = t1.id
LEFT JOIN table AS t2 ON t1.dependency = t2.id
LEFT JOIN table AS t3 ON t2.dependency = t3.id
LEFT JOIN table AS t4 ON t3.dependency = t4.id
....

这是一个疯狂的猜测只是为了与众不同,但无论如何我觉得它很漂亮。它至少和其他任何一个一样便携。但我不想密切关注;我想要使​​用合理的数据,开始测试,并检查明智的结果。

答案 4 :(得分:0)

Hierarchical query会:

SELECT * 
  FROM your_table
 START WITH id = :id_of_group_header_row
 CONNECT BY dependency = PRIOR id

查询的工作方式如下:

1。选择满足START WITH条件的所有行(此行现在为根)
2。选择满足CONNECT BY条件的所有行,
关键字PRIOR表示此列的值将从根行中获取 3。认为在步骤2中选择的行是根目录 4. 转到第2步,直到没有其他行