I have a MySQL table, as follows:
id | name | parent_id 19 | category1 | 0 20 | category2 | 19 21 | category3 | 20 22 | category4 | 21 ......
Now, I want a MySQL query, I only id [eg say 'id = 19'] then I should get all its sub-ID [ie, the result should have ids '20, 21,22 '] .... And children's grades do not know it can change ....
Also, I have to use a for loop solution ..... if possible, let me know how to use a single MySQL query to achieve the same functionality.
Solution :
1. If you are in MySql 8, then use the recursive where
clause:
with recursive cte (id, name, parent_id) as ( select id, name, parent_id from products where parent_id = 19 union all select p.id, p.name, p.parent_id from products p inner join cte on p.parent_id = cte.id ) select * from cte;
where
Specified value should be set to select all descendants of the parent is CONNECT BY
.
2. common table expressions that do not support MySql versions (up to version 5.7), you can use the following query to accomplish this:
select id, name, parent_id from (select * from products order by parent_id, id) products_sorted, (select @pv := '19') initialisation where find_in_set(parent_id, @pv) and length(@pv := concat(@pv, ',', id))
This is a violin.
Here, where
the value specified should be set to select all descendants of the parent is CONNECT BY
.