如何更新记录与同一个表中的另一条记录相同?

时间:2017-12-19 16:44:23

标签: mysql sql

我有一张这样的表:

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

这是预期的结果:

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

这是我的疑问:

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

但它抛出:

  

错误1093(HY000):您无法指定目标表'名称'用于FROM子句中的更新

我该怎么做?

2 个答案:

答案 0 :(得分:2)

您必须使用别名加入同一个表:

UPDATE names as t1
INNER join (select name from names where id = 1) t2
SET t1.name = t2.name
WHERE t1.id = 2

答案 1 :(得分:0)

你可以通过嵌套子查询来欺骗MySQL:

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

或者,您可以使用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