I have searched and found loads of examples but am still struggling to make this work.
I have the following table in SQLite:
SELECT * FROM TableA;
ID|USER|NAME|PARENT
1|User1|SomeName|-1
2|User1|SomeOtherName|1
3|User2|SomeName|-1
4|User2|SomeOtherName|-1
The PARENT for ID 2 with NAME of SomeOtherName is ID 1 - This is correct.
The PARENT for ID 4 with the NAME of SomeOtherName is ID -1 - This is incorrect. It should be ID 3.
I have many incorrect records like that (all with the same NAME of SomeOtherName and a PARENT of -1).
The column that ties them together is USER.
I need to update all the incorrect records with the correct parent ID.
I have tried the following to no avail:
DROP TABLE orphans;
CREATE TEMP TABLE orphans as
SELECT TableA.id, TableA.user, TableA.name FROM TableA WHERE TableA.name = 'SomeOtherName' AND TableA.parent = -1;
UPDATE TableA
SET parent = ( SELECT TableA.id
FROM TableA
INNER JOIN orphans
ON TableA.name = 'SomeName' AND orphans.user = TableA.user
)
WHERE TableA.user IN ( SELECT TableA.user
FROM TableA WHERE TableA.name = 'SomeOtherName' AND TableA.parent = -1 )
;
I just can't seem to get it right. Any help will be appreciated.