如何在UPDATE查询中使用同一表中的数据?

时间:2014-03-29 10:42:33

标签: mysql sql

update accounts set password=(select password from accounts where name='joongsu') 
where id=(select accountid from characters where name='Nobless')

它不能处理错误消息"您无法指定目标表'帐户'用于FROM子句"

的更新

为什么它不起作用?选择上面的查询只返回1行。

3 个答案:

答案 0 :(得分:1)

也许您应该尝试this one

UPDATE accounts
SET accounts.password =
(
    SELECT something.password
    FROM (SELECT * FROM accounts) AS something
    WHERE something.name='joongsu'
)
WHERE accounts.id=(SELECT accountid FROM characters WHERE name='Nobless');

这是一个黑客,但我测试了它,它适用于我的测试数据。出于某种原因,MySQL不允许在内部查询中使用与正在更新的表相同的表。

答案 1 :(得分:1)

UPDATE
    accounts AS account_to_be_updated
  JOIN 
    characters
      ON  characters.accountid = account_to_be_updated.id
      AND characters.name = 'Nobless'
  CROSS JOIN
    ( SELECT password
      FROM   accounts 
      WHERE  name = 'joongsu'
    ) AS existing_account
SET 
    account_to_be_updated.password = existing_account.password ;

答案 2 :(得分:0)

这是你想要的吗?

;with CTE as 
(
select password from accounts  where name='joongsu' limit 1
)
update accounts set password= CTE.password
    where id in 
(select accountid from characters where name='Nobless')