简体   繁体   中英

Update all table rows but top N in Mysql

I was trying to run the following query

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)

But Mysql doesn't allow 'LIMIT' in an 'IN' subquery.

I think I can make a select to count the table rows and then make an ordered update limited by 'COUNT - 10', but I was wondering if there is a better way.

Thanks in advance.

Try this:

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)

think i understood you right:

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;

EDIT

I've renamed the fields as you can't seem to take a hint !

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;

limit is not supported in subquery, what you will have to do is put the limit on the outer query with update query. this way it will update only 10 rows

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM