如何简化同一个表嵌套查询

时间:2015-05-13 09:05:22

标签: sql-server

我正在尝试按父ID计算第13(第N)级别的chield,我的查询在下面给出。 但执行时间太长。有没有更简单的方法呢?

查询是:

SELECT @count=COUNT(*) FROM member_introducer WHERE introducer_id IN(
 SELECT member_id FROM member_introducer WHERE introducer_id IN(
  SELECT member_id FROM member_introducer WHERE introducer_id IN(
   SELECT member_id FROM member_introducer WHERE introducer_id IN(
    SELECT member_id FROM member_introducer WHERE introducer_id IN(
     SELECT member_id FROM member_introducer WHERE introducer_id IN(
      SELECT member_id FROM member_introducer WHERE introducer_id IN(
       SELECT member_id FROM member_introducer WHERE introducer_id IN(
        SELECT member_id FROM member_introducer WHERE introducer_id IN(
         SELECT member_id FROM member_introducer WHERE introducer_id IN(
          SELECT member_id FROM member_introducer WHERE introducer_id IN(
           SELECT member_id FROM member_introducer WHERE introducer_id IN(
            SELECT member_id FROM member_introducer WHERE introducer_id = @parentId))))))))))))

1 个答案:

答案 0 :(得分:2)

您可以使用带有lvl列的递归CTE来表示子级别。这样的事情。

示例数据

DECLARE @member_introducer TABLE
(
member_id int,
introducer_id int
)

insert into @member_introducer VALUES(1,NULL)
insert into @member_introducer VALUES(2,1)
insert into @member_introducer VALUES(3,1)
insert into @member_introducer VALUES(4,2)
insert into @member_introducer VALUES(5,2)
insert into @member_introducer VALUES(6,3)
insert into @member_introducer VALUES(7,4)
insert into @member_introducer VALUES(8,5)
insert into @member_introducer VALUES(9,7)
insert into @member_introducer VALUES(10,8)
insert into @member_introducer VALUES(11,9)
insert into @member_introducer VALUES(12,10)
insert into @member_introducer VALUES(13,12)
insert into @member_introducer VALUES(14,13)
insert into @member_introducer VALUES(15,14)
insert into @member_introducer VALUES(16,15)
insert into @member_introducer VALUES(17,16)
insert into @member_introducer VALUES(18,17)
insert into @member_introducer VALUES(19,18)
insert into @member_introducer VALUES(20,19)

<强>查询

DECLARE @level int = 13;


;WITH CTE as
(
  SELECT CONVERT(INT,1) lvl,P.member_id
  FROM @member_introducer P
  WHERE P.introducer_id = 1

  UNION ALL

  SELECT CONVERT(INT,M.lvl + 1) lvl,P1.member_id
  FROM @member_introducer P1  
  INNER JOIN CTE  M
  ON M.member_id = P1.introducer_id
 )
SELECT COUNT(*)
FROM CTE 
WHERE lvl = @level

如果您的递归级别已修复,您甚至可以使用Zohar Peled建议的OPTION (MAXRECURSION 13)