我有一个表表,我需要使用一个子查询来更新列,该子查询使用的是同一列和同一表,并且该表始终会引发错误
#1093-您无法在FROM子句中指定要更新的目标表“ userdata”
这是我的表结构
# first_name username user_id manager employer
1 Obey Obeytalbot 5KNHEZW22P joekenpat joekenpat
2 Venantius Philian AYL67CIA8A MVKO6BLZL1 MVKO6BLZL1
3 Chidinma Chidinma 7LEJG9VQKN LUWY0AQ218 LUWY0AQ218
4 Victor Victron CQIIKUHME4 LUWY0AQ218 LUWY0AQ218
5 Francis FrancisRapheal LKDCRH3OAT OP4R245PX7 OP4R245PX7
我要执行的操作是使用select语句更新manager / employer
列:其中manager / employer
列的值为= user_id
列,然后返回username
该行作为更新manager / employer
字段的结果
这是我尝试过的:
UPDATE
userdata
set
manager = (
SELECT username from userdata
where user_id = manager LIMIT 1
),
employer = (
SELECT username from userdata
where user_id = employer LIMIT 1
)
答案 0 :(得分:1)
您需要在更新语句中进行自我联接:
update userdata u1
inner join userdata u2 on u2.user_id in (u1.manager, u1.employer)
set
u1.manager = case when u1.manager = u2.user_id then u2.username else u1.manager end,
u1.employer = case when u1.employer = u2.user_id then u2.username else u1.employer end