2

我是 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

我搜索了解决类似情况的解决方案,但我真的找不到,请帮忙

4

4 回答 4

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

注意:这将创建一个临时表,如果有大量行则查询变慢,请尝试使用索引/主键链接创建一个临时表(来源:Alex Comment

看到这个小提琴

于 2013-03-10T19:19:30.267 回答
2

尝试这个

   UPDATE fb_messages
   SET sent = 'Yes'
   WHERE sent = 'No'
   ORDER BY msg_id DESC
   limit 1
于 2013-03-10T19:07:12.560 回答
0

"In MySQL, you can't modify the same table which you use in the SELECT part. This behaviour is documented at: http://dev.mysql.com/doc/refman/5.6/en/update.html"

Break it up into two statements.

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

There's a workaround covered in the article below

Reference: MySQL Error 1093 - Can't specify target table for update in FROM clause

于 2013-03-10T19:22:18.103 回答
-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'
于 2013-11-04T08:27:52.270 回答