1

I have a long list from database which i want to update a field by name group. i want to update the first 30 to value '1' next 30 to value '2' and so on until the end

Any idea on how to go about it

$sql = mysqli_query($conn,
   "UPDATE `tablename` SET `group` = '$value' WHERE id IN (SELECT id FROM tablename ORDER BY id desc LIMIT 0, 30)");
5
  • what did you try so far? Commented Aug 1, 2016 at 7:57
  • what is the result of your query? Commented Aug 1, 2016 at 7:58
  • I think you should try with Stored Procedures Commented Aug 1, 2016 at 8:06
  • @tamil, stored procedures can definitely do this trick but it's probably over kill. Commented Aug 1, 2016 at 8:06
  • the second answer went well. but i had to repeat the process. i believe there has to be a php code with for i loop. or a do while loop. Commented Aug 8, 2016 at 10:17

2 Answers 2

3

You have run into this limitation of mysql

You cannot update a table and select from the same table in a subquery.

You could use an update join, but since limits are involved, you would once again run into the same issue. Since only a small number of records are involved, you could do a simple query to get the ids.

SELECT GROUP_CONCAT(id) FROM tablename ORDER BY id desc LIMIT 0, 30

Then use that in the next query

UPDATE `tablename` SET `group` = '$value' WHERE id IN (ids_from_above_query)

If you are worried about concurrent updates, start a transaction.

Sign up to request clarification or add additional context in comments.

Comments

2

If your update is a one-time thing (and don't need to optimize it, e.g. do it all in one query), you can simply repeat the following query until you are finished:

update `tablename` 
SET `group` = '$value' 
where `group` is null
order by id desc
limit 30;

All group-values have to be null (or some other unused value) to begin with, so e.g. use update tablename SET group = null first, if they aren't.

And you probably want to do it all in a transaction.

1 Comment

come to think of it, this is a better answer than mine +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.