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.
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.
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 .
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.
Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements along with expression operator.
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
UPDATE table2 SET name = (SELECT table1.Name FROM table1 WHERE table1.id = table2.id) WHERE apply_condition
UPDATE table2 t2, (SELECT id, name FROM table1) t1 SET t2.name = t1.name WHERE t1.id = t2.id
please read this link,another
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With