I have a MySQL table of following structure.
**Table elements :**
element_id element_name parent_id
1 UIG 0
2 CAM 1
3 IHG 1
4 USR 1
5 DBL 1
6 APD 1
7 RTM 1
8 OCR 2
9 IRT 3
10 ICR 3
11 OCR 2
12 USH 1
13 AML 1
I need to find child elements of a given element.
I made the following query :
SELECT parent_id,GROUP_CONCAT(element_id)
FROM elements
WHERE parent_id='1'
GROUP BY parent_id
which returns,
+-----------+--------------------------+
| parent_id | GROUP_CONCAT(element_id) |
+-----------+--------------------------+
| 1 | 2,3,4,5,6,7,12,13 |
+-----------+--------------------------+
1 row in set (0.00 sec)
While I need also need the childs of element 2 and 3, which should result into
+-----------+------------------------------------+
| parent_id | GROUP_CONCAT(element_id) |
+-----------+------------------------------------+
| 1 | 2,3,4,5,6,7,8,9,10,11,12,13 |
+-----------+------------------------------------+
1 row in set (0.00 sec)
How do I achieve this without procedures and just a query?
You just need to use the
inoperator on a subquery.** AS per OP’s comment the levels are definitely a concern**
However based on the initial sample data and request, here is the SQLFIDDLE DEMO that provides the results as per the question’s expected output.
The only change is that one needs to group by both
element_idandparent_idthe innner most first subquery.Not a very elegant query at all:
Results: