MySQL链式选择

时间:2016-03-17 10:55:13

标签: mysql

我有一张表family

+----------------------------+
| id | name   | age | parent |
|----------------------------|
| 1  | Father | 60  | NULL   |
|----------------------------|
| .. | ...... | ..  | .....  |
| N  | Luke   | 20  | N      |
+----------------------------+

parent是对family - id的引用。从父亲开始,如何使用单个选择查询选择他的最后一个后代?

很长的路要走n = SELECT * FROM family WHERE parent = 1然后o = SELECT * FROM family WHERE parent = n等等。

1 个答案:

答案 0 :(得分:1)

执行这样的递归查询:

select @pv:=id from family
join
(select @pv:=1)tmp
where parent=@pv

要获得最后一个后代,只需使用MAX聚合函数

SELECT MAX(@pv:=id) FROM family
JOIN
(SELECT @pv:=1)tmp
WHERE parent=@pv

更新:     换句话说。要获得祖先,请测试此查询

SELECT MIN(CASE WHEN parent IS NULL 
       THEN ID 
       ELSE @pv:=parent END) Ancestor
FROM family
JOIN
(SELECT @pv:=3)tmp
WHERE (CASE WHEN parent IS NULL OR id=@pv 
      THEN 1 ELSE 0 END) = 1