I need to execute this query it’s like ( main cats and sub cats )
Here is my schema:
++++++++++++++++++++++++++++++++
+ id | Country | Parent |
++++++++++++++++++++++++++++++++
+ 1 | India | |
++++++++++++++++++++++++++++++++
+ 2 | Usa | |
++++++++++++++++++++++++++++++++
+ 3 | California | Usa |
++++++++++++++++++++++++++++++++
+ 4 | New York | Usa |
++++++++++++++++++++++++++++++++
+ 5 | New Delhi | India |
++++++++++++++++++++++++++++++++
+ 6 | France | |
++++++++++++++++++++++++++++++++
And I want to get the result like this:
+++++++++++++++++++++++++++++++++++++++++++++++++
+ id | Country | Num | Childs |
+++++++++++++++++++++++++++++++++++++++++++++++++
+ 1 | India | 1 | New Delhi |
+++++++++++++++++++++++++++++++++++++++++++++++++
+ 2 | Usa | 2 | California,New York |
+++++++++++++++++++++++++++++++++++++++++++++++++
+ 3 | France | 0 | |
+++++++++++++++++++++++++++++++++++++++++++++++++
Try this:
HOW IT WORKS
My query is made of a main part and two subqueries (the ones between parenthesis); you can think of a subquery as a normal query executed in a main query returing to this some field (column). Subqueries can interact with main query because they can use main fields in SELECT or WHERE.
Main part gets all base countries (the ones without parent)
First subquery gets (for every item in main part) the count of countries whose parent is main item
Note that in
WHEREclause I ask to match subquery id with parent id, so I get only the count of countries related to main item.Second subquery is similar to first one, but a different field is returned using GROUP_CONCAT function to get all subcountries separated with commas.