`UPDATE` and `LIMIT` in `MySQL`

喜欢而已 提交于 2019-12-10 16:26:43

问题


I would like to update a specific range of rows, say starting from 30 and ending at 50. How may I achieve that.

I have tried with:

UPDATE tab
SET    col = 'somevalue' 
LIMIT 30, 50

but this doesn't work. Is there any way that I can update these rows?

The error that I get is:

Check the manual ... for the right syntax to use near ' 50'


回答1:


Your statement is not valid MySQL syntax and it doesn't make sense. The problem with the syntax is that offset is not supported for update statements (see here).

The problem with the logic is that you have no order by clause. MySQL doesn't guarantee the order of tables when processing them. So the "first" twenty rows and the "next" twenty" rows make no difference.

Why doesn't this do what you want?

UPDATE tab
  SET    col = 'somevalue' 
  LIMIT 20;

If you have a specific column that specifies the ordering, you can use where:

UPDATE tab
  SET    col = 'somevalue' 
  wHERE ID >= 30 and ID < 50;



回答2:


I think with update you can not use limit as it is in select(offset support), you will have to try like this:-

UPDATE tab
SET    col = 'somevalue' 
where id between 30 and 50;

LIMIT can be used with UPDATE but with the row count only, such as

UPDATE tab
SET    col = 'somevalue' 
where id > 30 
limit 20;

Similar question here.



来源:https://stackoverflow.com/questions/23183237/update-and-limit-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!