mysql - How to update foreign keys while inserting rows? -


i have 2 tables following layout ...

-------------    ------------------------- | master    |    | history               | -------------    ------------------------- | id | name |    | id | name | master_id | -------------    ------------------------- 

the history table contains rows master_id null. copy master table.

insert master (name) select name histories h h.master_id = null 

how can update master_id in history table id of associated object in master table? update should happen in same step insertion made. use mysql if of interest.

it possible insert master table records ids based on information other table.

for example, can use histories.id + last master.id:

lock tables master write, histories h write;  select id master order id desc limit 1 @last_master_id;  insert master (id, name)     select h.id + @last_master_id, h.name histories h;  update histories h set h.master_id = h.id + @last_master_id;  unlock tables; 

this works long use integer ids , if don't mind new id based on other one.

if wanted use non-deterministic ids, such uuids, solution require few more steps:

  • add temporary column histories table.
  • fill new ids (update histories set tmp_uuid = uuid(), that).
  • insert master select tmp_uuid histories...
  • update histories
  • drop temporary column.

one advantage of using uuids don't need lock tables. don't need worry other session inserting record , taking id, because other session generates different id.


Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

php - MySQLi multi_query results for later use -