0

I have a table like this:

// names
+----+-------+
| id |  name |
+----+-------+
| 1  | jack  |
| 2  |       |
+----+-------+

And here is the expected result:

// names
+----+-------+
| id |  name |
+----+-------+
| 1  | jack  |
| 2  | jack  |
+----+-------+

And here is my query:

update names set name = ( select name from names where id = 1 ) where id = 2

But it throws:

ERROR 1093 (HY000): You can't specify target table 'names' for update in FROM clause

How can I do that?

stack
  • 10,280
  • 19
  • 65
  • 117

2 Answers2

2

You have to join on the same table with an alias :

UPDATE names as t1
INNER join (select name from names where id = 1) t2
SET t1.name = t2.name
WHERE t1.id = 2
Daniel E.
  • 2,440
  • 1
  • 14
  • 24
0

You can either trick MySQL by nesting the subquery:

update names 
set name = select name from ( select name from names where id = 1 ) as t
where id = 2

or, you can use a CROSS JOIN:

UPDATE names n
CROSS JOIN (
  SELECT name FROM names WHERE id = 1) AS t
SET 
    n.name = t.name
WHERE id = 2  

Demo here

Giorgos Betsos
  • 71,379
  • 9
  • 63
  • 98