MySQL: Get Root Node of Parent Child Structure

I have a table like this:

=================
| Id | ParentId |
=================
| 1  | 0        |
-----+-----------
| 2  | 1        |
-----+-----------
| 3  | 0        |
-----+-----------
| 4  | 3        |
-----+-----------
| 5  | 3        |
-----+-----------
| 6  | 0        |
-----+-----------
| 7  | 6        |
-----+-----------
| 8  | 7        |
-----------------

Given Id, I need to know its root "node" Id. In this way,

  • Given 1, return 1
  • Given 2, return 1
  • Given 3, return 3
  • Given 4, return 3
  • Given 5, return 3
  • Given 6, return 6
  • Given 7, return 6
  • Given 8, return 7

Hierarchy levels are not limited. Is there any SQL that can do what I need?

+3
source share
5 answers

This is quite difficult to do in MySQL because it does not yet support recursive generic table expressions.

node .

0

, .

.sql script .

--
-- Create the `Nodes` table
--
CREATE TABLE `Nodes` (
     `Id` INT NOT NULL PRIMARY KEY
    ,`ParentId` INT NOT NULL
) ENGINE=InnoDB;

--
-- Put your test data into it.
--
INSERT INTO `Nodes` (`Id`, `ParentId`)
VALUES 
  (1, 0)
, (2, 1)
, (3, 0)
, (4, 3)
, (5, 3)
, (6, 0)
, (7, 6)
, (8, 7);

--
-- Enable use of ;
--
DELIMITER $$

--
-- Create the function
--
CREATE FUNCTION `fnRootNode`
(
    pNodeId INT
)
RETURNS INT
BEGIN
    DECLARE _Id, _ParentId INT;

    SELECT pNodeId INTO _ParentId;

    my_loop: LOOP
        SELECT 
             `Id`
            ,`ParentId`
        INTO 
             _Id
            ,_ParentId
        FROM `Nodes`
        WHERE `Id` = _ParentId;

        IF _ParentId = 0 THEN
            LEAVE my_loop;
        END IF;
    END LOOP my_loop;

    RETURN _Id;
END;
$$

--
-- Re-enable direct querying
--
DELIMITER ;


--
-- Query the table using the function to see data.
--
SELECT 
     fnRootNode(`Nodes`.`Id`) `Root`
    ,`Nodes`.`Id`
    ,`Nodes`.`ParentId`
FROM `Nodes`
ORDER BY 
    fnRootNode(`Nodes`.`Id`) ASC
;

-- EOF

:

Root Id   ParentId
==== ==== ========
1    1    0
1    2    1
3    3    0
3    4    3
3    5    3
6    6    0
6    7    6
6    8    7
+5

, , , foo <id>:

SELECT f.Id
FROM (
    SELECT @id AS _id, (SELECT @id := ParentId FROM foo WHERE Id = _id)
    FROM (SELECT @id := <id>) tmp1
    JOIN foo ON @id <> 0
    ) tmp2
JOIN foo f ON tmp2._id = f.Id
WHERE f.ParentId = 0
+1

@Kris , , node (), mysql , , :

DELIMITER $$

CREATE FUNCTION `FindRootNode`(InputValue INT(11)) RETURNS INT(11)
    NO SQL
BEGIN

DECLARE ReturnValue, _ParentId INT;

SELECT InputValue INTO _ParentId;

REPEAT
    SET ReturnValue = _ParentId;
    SELECT IFNULL((SELECT parent_id FROM TableName WHERE id=ReturnValue), 0) INTO _ParentId;

    UNTIL _ParentId = 0
END REPEAT;

RETURN ReturnValue;

END $$

DELIMITER ;

Usage1

SELECT CompanyCategoryTestRoot(HERE_COMES_CHILD_NODE_VALUE)
0

Source: https://habr.com/ru/post/1758286/


All Articles