1

How to display a specific record and its parents (maximum two)?

Table:
+---------------+
| id | parentID |
+---------------+
|  1 |     null |
|  2 |        1 |
|  3 |        1 |
|  4 |        2 |
|  5 |        2 |
|  6 |        2 |
+---------------+

The expected result:
Showing record with id 4 and his two parents

+---------------+
| id | parentID |
+---------------+
|  1 |     null |
|  2 |        1 |
|  4 |        2 |
+---------------+

I don't know how to do it. The following query doesn't work.

(SELECT `c1`.`parentID` FROM `table` as `c1` WHERE `c1`.`id` = 4 LIMIT 1) AS `c1parentID`,
(SELECT `c2`.`parentID` FROM `table` as `c2` WHERE `c2`.`id` = `c1parentID` LIMIT 1) AS `c2parentID`,
SELECT * FROM `table` as `c3` WHERE `c3`.`id` = `c1parentID` OR `c3`.`id` = `c2parentID` OR `c3`.`id` = 4

My knowledge of advanced queries is very poor. Please help :)

zeh
  • 10,130
  • 3
  • 38
  • 56
k0osl
  • 13
  • 2

1 Answers1

0

You will need CURSOR and LOOP. You will be looping from the child all the way up to the root (until parentId is NULL).

http://www.mysqltutorial.org/mysql-cursor/

Riad Baghbanli
  • 3,105
  • 1
  • 12
  • 20