Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Update values based on subquery

let's say I have select, which return me from table1:

ID  Name  1  Bob  2  Alice  3  Joe 

Then I want UPDATE values in another table based on this result:

UPDATE table2 SET Name = table1.Name WHERE ID = table1.ID 

As I understood, I can only do internal select in one place, like:

UPDATE table2 SET Name = (select Name from table1) WHERE ... 

And I don't know how to specify WHERE-condition.

like image 713
MasterClass Avatar asked Nov 26 '14 16:11

MasterClass


People also ask

Can we use subquery in UPDATE statement in MySQL?

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. No SPL routine in the subquery can reference the same table that UPDATE is modifying.

Can UPDATE be used in a subquery?

Like SELECT , the UPDATE statement can have a subquery in several places or clauses. In an UPDATE , the two clauses in which subqueries are used most commonly are SET and WHERE . The SET clause is where we define the new value for the column being modified by the UPDATE .

How do you UPDATE a column using subquery?

You can update the column specified in the SET clause with the value that a subquery returns. UPDATE orders SET ship_charge = (SELECT SUM(total_price) * . 07 FROM items WHERE orders.

Can subqueries be used in inserts deletes and/or updates?

Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements along with expression operator.


2 Answers

all you should do is just join the tables like this.

UPDATE table2 t2 JOIN table1 t1 ON t1.id = t2.id SET t2.name = t1.name; 

RESULTS WITH JOIN

if you are set on doing it with a select you could do it like this.

UPDATE table2 t2, (   SELECT Name, id      FROM table1  ) t1 SET t2.name = t1.name WHERE t1.id = t2.id 

RESULTS FROM SELECT

like image 126
John Ruddell Avatar answered Sep 17 '22 20:09

John Ruddell


 UPDATE table2  SET name = (SELECT table1.Name FROM table1 WHERE table1.id = table2.id)  WHERE apply_condition 

EDIT:#1

   UPDATE table2 t2, (SELECT id, name FROM table1) t1 SET t2.name = t1.name WHERE t1.id = t2.id 

please read this link,another

like image 23
Rajib Ghosh Avatar answered Sep 20 '22 20:09

Rajib Ghosh