我是MYSQL查询语句的新手,我目前仍然坚持使用以下代码
UPDATE fb_messages
SET sent = 'Yes'
WHERE msg_id = (SELECT MAX(msg_id) AS MSG_ID
FROM fb_messages
WHERE sent = 'No')
我收到此错误
#1093 - You can't specify target table 'fb_messages' for update in FROM clause
我搜索了一个解决方案,以解决类似的情况,但我真的找不到,请帮助
答案 0 :(得分:7)
这应该有用。
UPDATE fb_messages fb1, (SELECT MAX(msg_id) AS MSG_ID
FROM fb_messages
WHERE sent = 'No') fb2
SET sent = 'Yes'
WHERE fb1.msg_id = fb2.MSG_ID
注意:这将创建一个临时的,如果有大量的行然后查询变慢,请尝试使用索引/主键Link创建一个临时表(来源:亚历克斯Comment)
请参阅此fiddle
答案 1 :(得分:2)
试试这个
UPDATE fb_messages
SET sent = 'Yes'
WHERE sent = 'No'
ORDER BY msg_id DESC
limit 1
答案 2 :(得分:0)
“在MySQL中,您无法修改在SELECT部分中使用的同一个表。 此行为记录在:http://dev.mysql.com/doc/refman/5.6/en/update.html“
将其分为两个陈述。
CREATE TABLE Updates (
msg_id int
);
INSERT Updates (msg_id)
SELECT
MAX(msg_id)
FROM fb_messages
WHERE sent = 'No';
UPDATE fb_messages o, Updates u
SET o.sent = 'Yes'
WHERE o.msg_id = u.msg_id
下面的文章中介绍了一种解决方法
参考:MySQL Error 1093 - Can't specify target table for update in FROM clause
答案 3 :(得分:-1)
请在WHERE
条件
示例:
UPDATE t1
SET t1.Status = 5
WHERE t1.SearchID NOT IN
(SELECT TMP.SearchID FROM
(SELECT MIN(t1.SearchID) AS SearchID
FROM t1
WHERE t1.ID = '750') TMP)
AND t1.ID = '750'