patternsqlModerate
query regarding combining an update and an insert query into a single query in mysql
Viewed 0 times
combiningupdateinsertintoqueryregardingmysqlsingleand
Problem
i want to track history of changes for a user, so that whenever he changes his profile, i need to take the old data and store in history and update with new data.
I can use a
can i have all these in a single query in mysql without using stored procedures, triggers, etc.. like using locks etc.. if so give me a small sample.
I can use a
select to get the old data, an insert to history and finally an update to change data.can i have all these in a single query in mysql without using stored procedures, triggers, etc.. like using locks etc.. if so give me a small sample.
Solution
To do this without the risk of blocking another user trying to update the same profile at the same time, you need to lock the row in
t1 first, then use a transaction (as Rolando points out in the comments to your question) :start transaction;
select id from t1 where id=10 for update;
insert into t2 select * from t1 where id=10;
update t1 set id = 11 where id=10;
commit;Code Snippets
start transaction;
select id from t1 where id=10 for update;
insert into t2 select * from t1 where id=10;
update t1 set id = 11 where id=10;
commit;Context
StackExchange Database Administrators Q#3555, answer score: 13
Revisions (0)
No revisions yet.