How to check the column value of all parent record of a child in SQL

Nya Nguyen :

Lets say we have a single table with 3 columns: ID, PARENT_ID and VALUE.

We have for example 8 records:

ID PARENT_ID VALUE
A  NULL      1
B  A         1
C  B         0
D  C         1
E  D         1
F  E         1
G  F         1
H  G         0   

How can we check using a SQL query or stored procedure (for MySQL preferably) if any of the parent record for record with ID "G" has a value of 0? If a parent from the chain has 0 for VALUE, there is no need to check further back.

This has to work by taking any child ID and look at the entire chain of its parents before that child. Some child could have no parents or could also have a chain of parents and a parent record can have 0 or many child records.

In this example, the search would end at record with ID "C" (ie: return that ID is fine) since it is the parent record of the chain of parents (for G) that is 0 for VALUE.

Bill Karwin :

Here's an example of a MySQL 8.0 recursive CTE query that does what you describe, traverse the ancestors of 'G' and return those that have a value = 0:

with recursive cte as (
  select * from mytable where id = 'G'
  union all
  select t.* from cte join mytable t on t.id = cte.parent_id
) select * from cte where value = 0;

+------+-----------+-------+
| id   | parent_id | value |
+------+-----------+-------+
| C    | B         |     0 |
+------+-----------+-------+

Read https://dev.mysql.com/doc/refman/8.0/en/with.html for more about recursive CTE queries.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=371589&siteId=1