SQL Copy set - 'clone' with FK updates
I need to copy a set of data that has parentID as a field... so when I take a set of existing records and insert them, I'll need their parentID to REFLECT the NEW PK - not the old one.
I'm curious if there is a SQL way to do this - currently I'm doing a bunch of logic @ the application layer and updating the records - so I'm storing the OLD recordset, and doing a lookup based on old ID, old parent ID...
heck - maybe there is a 'clone' or 'copy & update FK' - I'm using MySQL 5
a dataset may look like this
+--------+---------+------+
| ID(pk) | PID(FK) | NAME |
+--------+---------+------+
| 3123 | 0 | Bob |
+--------+---------+------+
| 3127 | 0 | Jim |
+--------+---------+------+
| 3400 | 3123 | Sue |
+--------+---------+------+
| 3123 | 0 | Rik |
+--------+---------+------+
| 3127 | 3400 | Cara |
+--------+---------+------+
| 3400 | 3400 | Pat |
+--------+---------+------+
So the copied records might take on these IDs -where the PIDs in () are the unknown values that I need to know HOW to derive. they cannot be presumed to be sequential or singular.
+--------+---------+------+
| ID(pk) | PID(FK) | NAME |
+--------+---------+------+
| 4000 | 0 | Bob |
+--------+---------+------+
| 4001 | 0 | Jim |
+--------+---------+------+
| 4002 | (4000) | Sue |
+--------+---------+------+
| 4003 | 0 | Rik |
+--------+---------+------+
| 4004 | (400开发者_如何学Go2) | Cara |
+--------+---------+------+
| 4005 | (4002) | Pat |
+--------+---------+------+
精彩评论