Google面试问题:针对以下方案的递归查询或公用表表达式

时间:2011-06-17 17:18:20

标签: sql sql-server-2005 recursion common-table-expression

我有两个表TableA和TableB,方式如下:

Table A(ID, PairId)
--Here the Pair represented by PairId will always have 2 elements in it.

Data:
100,1
101,1
----- 
104,2
109,2



TableB(A.ID, GroupId)
--Here the Group represented by GroupId will may have any number of elements. 
--Also, A.ID means its a foriegn key from TableA
Data:
100,1000
102,1000
103,1000
--------
101,1001
104,1001
105,1001
-------
105,1002
106,1002
107,1002

给定表A中的id(比如X), 找到其配对的ids, 然后是队友(以前的同伴) 然后是配偶(我们在前一步中找到的所有配偶) 和他们的同伴(我们在前一步中找到的所有人)等等.... 直到你找不到任何伴侣或同伴。

For instance, given X as 100
you will accumulate data in this fashion:

Include PairMates
100
101

Include GroupMates(of all the ones in prevstep)
100--groupmates of 100
102
103
101--groupmates of 101
104
105

Include PairMates(of all the ones in the prevstep)
100
102
103
101
104--Pairmate of 104
109
105

Include Groupmates(of all the ones in the prev step)
100
102
103
101
104
109
105--Groupmates of 105
106
107

Include Pairmates( of all the ones in the prevstep)
100
102
103
101
104
109
105
106
107
[None found]
Include Groupmates( of all the ones in the prevstep)
100
102
103
101
104
109
105
106
107
[Nonefound]
---since no pairmates and groupmates were added so the recursion ends

1 个答案:

答案 0 :(得分:0)

DECLARE @ID INT  = <Given ID>

WITH CTE AS
(
SELECT * FROM TABLEB 
WHERE ID IN (SELECT ID FROM TABLEA WHERE pairID IN (SELECT pairId FROM TABLEA WHERE ID = @ID)) 
UNION 
SELECT * FROM TABLEB WHERE GroupID IN (SELECT GroupID FROM CTE)
)
SELECT * FROM CTE