There is a table
EDIT: The previous table was not clear because of the id and field_id being the same That is the reason why the solution below given by you guys didnt work.
The parent_id which is stored is not the field_id but the ID generated automatically.
So in this case, all the 3 columns have to be taken into consideration.
In the other cases, the field_id is actually used to construct the sql.
But in this case, the id of the table is stored as the parent_id and not the field_id.
-------------------------
id | field_id | parent_id |
---------------------------
1 10 0
2 11 1
3 12 1
4 13 2
5 14 2
6 15 2
7 16 2
8 17 4
I m having this table in which the field_id and parent_ids are present. I need to get all the field_id and all of their children and grandchildrens.
So i found this code below on stackoverflow. but couldn't use it in mysql as im using an older version and also there is a difference in my case. (using 3 columns instead of 2)
My version of mysql doesnot support with.
How can we rewrite the query without using WITH statement.
Thanks in advance.
DECLARE @Id int = your_UnitId
;WITH cte AS
(
SELECT a.Id, a.parentId, a.name
FROM customer a
WHERE Id = @Id
UNION ALL
SELECT a.Id, a.parentid, a.Name
FROM customer a JOIN cte c ON a.parentId = c.id
)
SELECT parentId, Id, name
FROM cte