Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql update two tables at once

I have two tables that need the exact same values for denormalization purposes.

Here's the query.

first table

UPDATE Table_One  SET win = win+1, streak = streak+1, score = score+200  WHERE userid = 1 AND lid = 1 LIMIT 1 

second table

UPDATE Table_Two  SET win = win+1, streak = streak+1, score = score+200  WHERE userid = 1 LIMIT 1 

As you can see the only difference between both tables is their name and table two doesn't have the field lid

Anyway to combine both updates to just one?

like image 510
user962449 Avatar asked Jan 06 '12 22:01

user962449


People also ask

How do I update 2 tables simultaneously?

You can't update two tables at once, but you can link an update into an insert using OUTPUT INTO , and you can use this output as a join for the second update: DECLARE @ids TABLE (id int); BEGIN TRANSACTION UPDATE Table1 SET Table1. LastName = 'DR.

Can we update multiple tables using update command?

In SQL, there is a requirement of a single query/statement to simultaneously perform 2 tasks at the same time. For instance, updating 2 different tables together in a single query/statement. This involves the use of the BEGIN TRANSACTION clause and the COMMIT clause.

Can you update data in two base tables of a view with a single update statement?

Updating a View The UPDATE statement can only reference columns from one base table. This means it's not possible to update multiple tables at once using a single UPDATE statement.


1 Answers

It should be possible with a multi-table update, as described in the documentation.

http://dev.mysql.com/doc/refman/5.5/en/update.html

UPDATE Table_One a INNER JOIN Table_Two b ON (a.userid = b.userid) SET   a.win = a.win+1, a.streak = a.streak+1, a.score = a.score+200,   b.win = b.win+1, b.streak = b.streak+1, b.score = b.score+200  WHERE a.userid = 1 AND a.lid = 1 AND b.userid = 1 

Note: Multi-table doesn't support LIMIT, so this could cause more grief depending on the details.

Stored procedures or transactions may be a nicer solution.

like image 53
rrehbein Avatar answered Oct 09 '22 22:10

rrehbein