MySQL - Clone a row and all its children -


i have table named users. table linked agendas, linked events.

an agenda can have 0 or n event.

so now, if want clone user #3 of agendas , events, keeping foreign keys date?

i know how multiple queries (select insert, inserted_id , on...), have no clue how in single query.

i found how copy user's row, not children:

create temporary table tmp_users select * users userid = 3; update tmp_users set userid = null; insert users select * tmp_users; drop temporary table if exists tmp_users; 

so if got idea, 'm not pro of mysql , don't event know if that's possible ... :)

imho you're looking this

insert users (user_name, ...) select user_name, ...   users  user_id = 3;  set @last_user_id = last_insert_id();  insert agendas (user_id, agenda_name, ...) select @last_user_id, agenda_name, ...   agendas  user_id = 3;  insert events (agenda_id, event_name, ...) select a3.agenda_id_new, e.event_name, ...   events e join (select a1.agenda_id agenda_id_old,         a2.agenda_id agenda_id_new   (select agenda_id, @n := @n + 1 n     agendas, (select @n := 0) n    user_id = 3 order agenda_id) a1 join (select agenda_id, @m := @m + 1 m     agendas, (select @m := 0) m    user_id = @last_user_id order agenda_id) a2 on a1.n = a2.m) a3       on e.agenda_id = a3.agenda_id_old; 

sqlfiddle

the assumption tables have id columns (user_id, agenda_id, event_id) set auto_increment

and can wrap stored procedure input parameter of user being cloned.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -