MySQL - UPDATE query with LIMIT
In addition to the nested approach above, you can accomplish the application of theLIMIT
using JOIN
on the same table:
UPDATE `table_name`
INNER JOIN (SELECT `id` from `table_name` order by `id` limit 0,100) as t2 using (`id`)
SET `name` = 'test'
In my experience the mysql query optimizer is happier with this structure.
If you want to update multiple rows using limit in MySQL you can use this construct:
UPDATE table_name SET name='test'
WHERE id IN (
SELECT id FROM (
SELECT id FROM table_name
ORDER BY id ASC
LIMIT 0, 10
) tmp
)
I would suggest a two step query
I'm assuming you have an autoincrementing primary key because you say your PK is (max+1) which sounds like the definition of an autioincrementing key.
I'm calling the PK id
, substitute with whatever your PK is called.
1 - figure out the primary key number for column 1000.
SELECT @id:= id FROM smartmeter_usage LIMIT 1 OFFSET 1000
2 - update the table.
UPDATE smartmeter_usage.users_reporting SET panel_id = 3
WHERE panel_id IS NULL AND id >= @id
ORDER BY id
LIMIT 1000
Please test to see if I didn't make an off-by-one error; you may need to add or subtract 1 somewhere.
When dealing with null, =
does not match the null values. You can use IS NULL
or IS NOT NULL
UPDATE `smartmeter_usage`.`users_reporting`
SET panel_id = 3 WHERE panel_id IS NULL
LIMIT
can be used with UPDATE
but with the row count
only