I have categories table like below:
category_id name parent_id
1 category1 NULL
2 subcategory1 1
3 category2 NULL
4 subcategory2 1
5 subcategory4 NULL
6 subcategory3 1
7 subcategory8 NULL
8 subcategory9 5
9 subcategory5 6
10 subcategory10 6
11 subcategory13 6
12 subcategory6 4
13 subcategory7 4
14 subcategory12 4
15 subcategory17 4
16 subcategory10 4
17 subcategory19 4
I want to fetch data of all those parents who are having at least one child and fetch all children's data first 2 rows per parent.
Below is the effort I tried until now.
SELECT c.category_id, c1.name,
FROM categories c
LEFT JOIN categories c1 ON c1.category_id = c.category_id where count(c1.id) > 1
limit 2;
My expected output:
category_id parent_id name parent_name
2 1 subcategory1 category1
4 1 subcategory2 category1
8 5 subcategory9 subcategory4
9 6 subcategory5 subcategory3
10 6 subcategory10 subcategory3
12 4 subcategory6 subcategory2
13 4 subcategory7 subcategory2