I am using MySQL 5.6.17.
I have a self-referencing table TableA with columns id (PK), title (varchar), type (varchar), parent_id (FK that refers to id of the same table).
The sample data is as below :
id title type parent_id
1 abc G NULL
2 def G NULL
3 xyz G NULL
4 pqr G NULL
5 abc T NULL
6 def T NULL
7 xyz T NULL
8 pqr T NULL
Now, I want each record having type='G' should become the child of the record with type='T' having the same title.
So the resultant table data should be :
id title type parent_id
1 abc G 5
2 def G 6
3 xyz G 7
4 pqr G 8
5 abc T NULL
6 def T NULL
7 xyz T NULL
8 pqr T NULL
I've tried query below :
UPDATE TableA
SET parent_id = (SELECT id FROM ( SELECT id FROM TableA WHERE TYPE='T' ) d)
WHERE TYPE='G';
But it returns
Error Code: 1242
Subquery returns more than 1 row
I also have tried :
UPDATE TableA t1
SET t1.parent_id = t2.newlocalid
INNER JOIN (
SELECT title, id AS newlocalid
FROM TableA t2
WHERE TYPE='T'
) t2 ON t1.title = t2.title
WHERE t1.type='G'
But it also returns the error in Syntax.
Can anyone help me to achieve it?