How to return 'Father ID' in this query?

77 views Asked by At

I'm trying to return the father ID of my table (MySQL), this is the return:

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

I need this:

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

Here is the fiddle

1

There are 1 answers

0
Alessandro Gomes On BEST ANSWER

I had to use a function like this (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.