0

我的表 tbl1 需要一个 sql 查询

像这样的表的示例内容

                        serial   ida    idb        
                          1        1       2             
                          2        1       3              
                          3        3       7             
                          4        3       6              
                          5        2       4               
                          6        2       6              

.

在表 tbl1 列 ida 和 idb 相关,例如 1 与 2 和 3 相关,2 与 4 和 6 相关

ida 值 1 的相关数据是 2 和 3,我想选择 1 的相关数据(2 和 3)的相关数据。

2 和 3 的相关数据是 7, 6 和 4, 6。所以输出将是 (7,6,4)
。我需要一个 sql 查询来显示这个输出。任何人都可以分享一些想法如何做到这一点..

4

3 回答 3

0
SELECT DISTINCT idb FROM tbl1 WHERE ida = 2 OR ida = 3;

这是你要找的吗?

于 2012-06-02T11:39:02.807 回答
0
select distinct idb from tbl1 where ida in (select idb from tbl1 where ida = 1)
于 2012-06-04T11:45:23.000 回答
0

编辑:更正了确定层次结构的子分支。

这可能有一些用处:

-- Sample data.
declare @Table as table ( serial int identity, ida int, idb int )
insert into @Table ( ida, idb ) values
  ( 1, 2 ), ( 1, 3 ),
  ( 3, 7 ), ( 3, 6 ),
  ( 2, 4 ), ( 2, 6 )

select * from @Table

-- Demonstrate recursive query.
; with CTE as (
  -- Start with ida = 1.
  select serial, ida, idb, 1 as depth, path = cast( right( '000000' + cast( ida as varchar(6) ), 6 ) as varchar(1024) )
    from @Table
    where ida = 1
  union all
  -- Add each row related to the most recent selected row(s).
  select T.serial, T.ida, T.idb, C.depth + 1, cast( C.path + right( '000000' + cast( T.ida as varchar(6) ), 6 ) as varchar(1024) )
    from CTE as C inner join
      @Table as T on T.ida = C.idb
  )
-- Show everything.
select *
  from CTE

-- Repeat the recursive query.
; with CTE as (
  -- Start with ida = 1.
  select serial, ida, idb, 1 as depth, path = cast( right( '000000' + cast( ida as varchar(6) ), 6 ) as varchar(1024) )
    from @Table
    where ida = 1
  union all
  -- Add each row related to the most recent selected row(s).
  select T.serial, T.ida, T.idb, C.depth + 1, cast( C.path + right( '000000' + cast( T.ida as varchar(6) ), 6 ) as varchar(1024) )
    from CTE as C inner join
      @Table as T on T.ida = C.idb
  )
-- Select only the deepest children.
select distinct idb
  from CTE as C
  where not exists ( select 42 from CTE where left( path, len( C.path ) ) = C.path and len( path ) > len( C.path ))
  order by idb

左边作为练习是旋转结果。

于 2012-06-02T14:15:50.163 回答