如何在此查询中返回“父亲ID”?

时间:2014-12-05 16:18:28

标签: mysql sqlfiddle

我正在尝试返回我的表(MySQL)的父ID,这是返回:

ID  NOME         PARENT_ID
1   Project      (null)
2   Sub          1
3   Sub-Sub      2
4   Sub-Sub-Sub  3

我需要这个:

ID  NOME         PARENT_ID FATHER_ID
1   Project      (null)    (null)
2   Sub          1         1 
3   Sub-Sub      2         1
4   Sub-Sub-Sub  3         1

以下是fiddle

1 个答案:

答案 0 :(得分:0)

我必须使用这样的函数(link SO PT-BR):

CREATE FUNCTION getRoot(idSearch INT)
RETURNS INT DETERMINISTIC
BEGIN
  SET @idParent = idSearch;
  WHILE (@idParent != 0) DO
    SET @idFound = @idParent;
    SET @idParent = (SELECT id_parent FROM arvore WHERE id = @idParent);
  END WHILE;
  RETURN @idFound;
END

<强> SQL Fiddle

<强> SQL Fiddle2