日期:2014-05-18  浏览次数:20390 次

请教一个数据有嵌套的查询语句
有表数据如下:
a b
--------------------
11 1
11 2
12 11
12 3
13 11
13 12

执行查询a=13的结果:
a b
--------------------
13 1
13 2
13 3

------解决方案--------------------
SQL code
--------------------------------------
--  Author : htl258(Tony)
--  Date   : 2010-04-27 11:25:06
--  Version:Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) 
--          Jul  9 2008 14:43:34 
--          Copyright (c) 1988-2008 Microsoft Corporation
--          Developer Edition on Windows NT 5.1 <X86> (Build 2600: Service Pack 3)
--  Blog   : http://blog.csdn.net/htl258
--------------------------------------
--> 生成测试数据表:tb

IF NOT OBJECT_ID('[tb]') IS NULL
    DROP TABLE [tb]
GO
CREATE TABLE [tb]([a] INT,[b] INT)
INSERT [tb]
SELECT 11,1 UNION ALL
SELECT 11,2 UNION ALL
SELECT 12,11 UNION ALL
SELECT 12,3 UNION ALL
SELECT 13,11 UNION ALL
SELECT 13,12
GO
--SELECT * FROM [tb]

-->SQL查询如下:
declare @i int
set @i=13
;with t as
(
    select * from tb where a=@i
    union all
    select a.* from tb a join t b on b.b=a.a
)
select distinct @i a,b 
from t a 
where not exists(select 1 from t where a.b=a)
order by b
/*
a           b
----------- -----------
13          1
13          2
13          3

(3 行受影响)
*/