我有以下查询:
UPDATE lessonstatus
INNER JOIN user ON lessonstatus.user_id = user.user_id
SET user_id = (SELECT user_id FROM user WHERE username = 'too_many_accounts')
WHERE last_name = 'stupid'
AND first_name = 'user'
AND username != 'too_many_accounts'
AND lessonstatus.lesson_id NOT IN (SELECT lesson_id FROM lessonstatus WHERE user_id = 1);
但是,尝试执行时会出现以下错误:
Error Code : 1093
You can't specify target table 'lessonstatus_rtab' for update in FROM clause
如何修复此查询以使其有效?
答案 0 :(得分:3)
您不能在表中(即使在子查询中)SELECT
在同一查询中更新。这就是错误“无法指定目标表”的意思。
但您可以在user
语句中多次加入lessonstatus
和UPDATE
,并创造性地使用加入条件来挑选您想要的各个行。
使用联接模拟NOT IN
的方法是LEFT OUTER JOIN
。如果该联接的右侧不匹配,那么NOT IN
将成立。
UPDATE lessonstatus l1
INNER JOIN user u1 ON (l1.user_id = u1.user_id)
INNER JOIN user u2 ON (u2.username = 'too_many_accounts')
LEFT OUTER JOIN lessonstatus l2
ON (l1.lesson_id = l2.lesson_id AND l2.user_id = 1)
SET l1.user_id = u2.user_id
WHERE u1.last_name = 'stupid' AND u1.first_name = 'user'
AND u1.username != 'too_many_accounts'
AND l2.lesson_id IS NULL; -- equivalent to "l NOT IN l2"
nb:我已经测试了此查询的语法,但没有测试真实数据。无论如何,它应该让你开始。
答案 1 :(得分:0)
还有更多错误(“user”表和“user_rtab”别名不匹配,建议不要使用非限定字段名称),但UPDATE语法本身应该类似:
UPDATE lessonstatus
SET user_id = (SELECT TOP 1 user_id FROM user WHERE username = 'too_many_accounts')
FROM lessonstatus
INNER JOIN user ON lessonstatus.user_id = user_rtab.user_id
WHERE last_name = 'stupid'
AND first_name = 'user'
AND username != 'too_many_accounts'
AND lessonstatus.lesson_id NOT IN (
SELECT lesson_id FROM lessonstatus WHERE user_id = 1
);