仅根据特定条件返回树的一个路径

时间:2015-12-09 16:51:19

标签: mysql recursive-query

鉴于此表:

CREATE TABLE customer
 (
  id int,
  parentid int,
  name nvarchar(10)
  )

INSERT customer
VALUES(1,  NULL, 'aaa'),
      (2,  1,    'bbb'),
      (3,  2,    'ccc'),
      (4,  2,    'ddd'),
      (5,  1,    'eee'),
      (6,  5,    'fff'),
      (7,  5,    'ggg'),
      (8,  1,    'hhh'),
      (9,  8,    'iii'),
      (10, 8,    'jjj')

我想要一个分支路径而不是特定id的整个分支。例如,这将返回特定id的所有子项:

DECLARE @Id int = your_UnitId
;WITH cte AS 
 (
  SELECT a.Id, a.parentId, a.name
  FROM customer a
  WHERE Id = @Id
  UNION ALL
  SELECT a.Id, a.parentid, a.Name
  FROM customer a JOIN cte c ON a.parentId = c.id
  )
  SELECT parentId, Id, name
  FROM cte

SQLFiddle上的演示

我希望,例如,使用' aaa',' hhh',' jjj'返回行。当your_UnitId为1时,因为该单个分支具有最高的ID。 (' hhh'其兄弟姐妹的id最高,jjj'其兄弟姐妹的id最高。)

1 个答案:

答案 0 :(得分:0)

Fisrt,你必须删除工作台上的一些客户才能保留长子。然后你可以使用你的递归CTE。您无法在递归CTE中过滤客户。

DECLARE @Id int = 1

;with biggest_customer as
(
Select Id = max(a.Id), ParentId = a.parentId  
FROM customer a 
group by a.parentId
UNION
Select Id = a.Id, ParentId = a.parentId FROM customer a where a.ID = @ID   
),

biggest_customer_name as
(
select b.*, c.name from biggest_customer b inner join customer c on b.ID=c.ID
),

cte AS 
(
SELECT a.Id, a.parentId, a.name
FROM biggest_customer_name a
WHERE Id = @Id
UNION ALL
SELECT a.Id, a.parentid, a.Name
FROM biggest_customer_name a JOIN cte c ON a.parentId = c.id

)
SELECT parentId, Id, name
FROM cte