我需要为我的表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 s相关数据是2和3,我想选择1的相关数据(2和3)的相关数据。
2和3 s相关数据是7,6和4,6。因此输出将是(7,6,4)
。我需要一个SQL查询来显示此输出。任何人都可以分享一些如何做到这一点......
答案 0 :(得分:0)
SELECT DISTINCT idb FROM tbl1 WHERE ida = 2 OR ida = 3;
这是你在找什么?
答案 1 :(得分: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
左边的练习正在转动结果。
答案 2 :(得分:0)
select distinct idb from tbl1 where ida in (select idb from tbl1 where ida = 1)