Show create table:
CREATE TABLE `a` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`parent_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `parent_id` (`parent_id`),
CONSTRAINT `a_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `a` (`id`) ON DELETE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Select:
+----+---------+-----------+
| id | name | parent_id |
+----+---------+-----------+
| 1 | World | 1 |
| 2 | Europe | 1 |
| 3 | USA | 1 |
| 4 | France | 2 |
| 5 | Germany | 2 |
+----+---------+-----------+
Question:
-
how do I best define a function which, passed id 4 as an argument, returns:
"World > Europe > France"
This hierarchical "nesting" by "parent_id" could be arbitrarily deep, not just 3 levels deep.
Best Answer
You can use the following function for returning Hierarchical structure for N no:of leaf nodes like "World > Europe > France > S1 > S2"
Try out