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 value 1 の関連データは 2 と 3 で、1 の関連データ (2 と 3) の関連データを選択したい。

2 と 3 の関連データは 7, 6 と 4, 6 です。したがって、出力は (7,6,4) になり
ます。この出力を表示するには、SQL クエリが必要です。誰かがそれを行う方法についていくつかのアイデアを共有できますか..

4

3 に答える 3

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 に答える
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 に答える