Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql - Update table using select statment from same table

Tags:

mysql

I'm trying to update row in a table using values from a different row (and different columns) in the same table. Something along the lines of this, although my syntax produces no results: Here is the code (updated):

UPDATE table1 AS t1 INNER JOIN (SELECT field_id_46,field_id_47 FROM table1 WHERE entry_id = 36) AS t2 SET t1.field_id_60 = t2.field_id_46, t1.field_id_61 = t2.field_id_47 WHERE t1.entry_id = 45; 
like image 248
user1368392 Avatar asked May 01 '12 18:05

user1368392


People also ask

Can we do an UPDATE from a select statement?

The UPDATE from SELECT query structure is the main technique for performing these updates. An UPDATE query is used to change an existing row or rows in the database. UPDATE queries can change all tables' rows, or we can limit the update statement affects for certain rows with the help of the WHERE clause.

Can we use subquery in UPDATE statement?

UPDATE operations with subqueries that reference the same table object are supported only if all of the following conditions are true: The subquery either returns a single row, or else has no correlated column references. The subquery is in the UPDATE statement WHERE clause, using Condition with Subquery syntax.


2 Answers

update table as t1 inner join ( select field_id_46,field_id_47 from table where entry_id = 36) as t2 set t1.field_id_60 = t2.field_id_46,     t1.field_id_61 = t2.field_id_47 where t1.entry_id = 45 

or, simply

update table as t1, ( select field_id_46,field_id_47 from table where entry_id = 36) as t2 set t1.field_id_60 = t2.field_id_46,     t1.field_id_61 = t2.field_id_47 where t1.entry_id = 45 
like image 154
Nicola Cossu Avatar answered Sep 20 '22 20:09

Nicola Cossu


Adding..

Same tables, with more of one registers

UPDATE table t1 INNER JOIN table t2 ON t2.entry_id = t1.entry_id SET t1.field_id_60 = t2.field_id_60,     t1.field_id_61 = t2.field_id_61 
like image 33
Diego Avatar answered Sep 19 '22 20:09

Diego