更新所有表行但在Mysql中排在前N位

时间:2011-01-09 14:37:33

标签: sql mysql

我试图运行以下查询

UPDATE blog_post SET `thumbnail_present`=0, `thumbnail_size`=0, `thumbnail_data`=''
WHERE `blog_post` NOT IN (
 SELECT `blog_post`
 FROM blog_post
 ORDER BY `blog_post` DESC
 LIMIT 10)

但是Mysql不允许'IN'子查询中的'LIMIT'。

我想我可以选择计算表格行,然后按“COUNT - 10”进行有序更新,但我想知道是否有更好的方法。

提前致谢。

3 个答案:

答案 0 :(得分:1)

试试这个:

UPDATE blog_post SET `thumbnail_present`=0, `thumbnail_size`=0, `thumbnail_data`=''
WHERE `blog_post` NOT IN (
    SELECT `blog_post` FROM
    (
     SELECT `blog_post`, (@rowNum := @rowNum + 1) rn
     FROM blog_post, (SELECT @rowNum :=0) b
     ORDER BY `blog_post` DESC
     ) a
 WHERE rn <= 10)

答案 1 :(得分:1)

我认为你理解正确:

update blog_post bp
left outer join
(
select 
 post_id -- what's your PK again ??
from 
 blog_post
order by
 post_id desc limit 10
) latest on latest.post_id = bp.post_id
set 
  bp.thumbnail_present = 0 -- add more fields
where
 latest.post_id is null;

修改

我已经重命名这些字段,因为你似乎无法提示!

update blog_post bp
left outer join
(
select 
 blog_post 
from 
 blog_post
order by
 blog_post desc limit 10
) latest on latest.blog_post = bp.blog_post
set 
  bp.thumbnail_present = 0
where
 latest.blog_post is null;

答案 2 :(得分:0)

子查询中不支持

limit,您需要做的是使用更新查询对外部查询设置限制。这样它只会更新10行