3

I have figured out how to do a batch update when the value is the same for each record using:

UPDATE tbl SET col1='foo1' WHERE id IN (1,2,3)

If I have a comma delimited string of values, that match up to the ids, can I do a batch update that updates the values differently as in

UPDATE tbl SET col1='1,0,1' WHERE id IN (1,2,3)

Thanks for suggestions:

Edit:

The html page that sends the data to this query consists of checkboxes as follows:

<input type="checkbox" name="id[]" value="1"><input type="hidden" name="col1[]" value=0> 
<input type="checkbox" name="id[]" value="2"><input type="hidden" name="col1[]" value=1>
<input type="checkbox" name="id[]" value="3"><input type="hidden" name="col1[]" value=0>

etc. up to 20 boxes.

On the server side, the posted arrays are converted to comma delimited strings using implode so I end up with the two strings, 1,0,1 for the values and 1,2,3 for the ids. But the user could check up to 20 boxes from this page. Maybe I have to manipulate the arrays somehow. Note in the real example, the ids are not 1,2,3, but could be something like 221, 433, 512, 600 etc., depending on what user checks

2 Answers 2

8

the second query will update each row 1, 2,3 to the same value '1,0,1'

i think what you need is

  UPDATE mytable
    SET myfield = CASE other_field
        WHEN 1 THEN 'value'
        WHEN 2 THEN 'value'
        WHEN 3 THEN 'value'
    END 
WHERE id IN (1,2,3) 

reference http://www.karlrixon.co.uk/writing/update-multiple-rows-with-different-values-and-a-single-sql-query/

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

1 Comment

do you need to iterate a new When case for each element you get. Number of elements/ids is unknown as it is coming from a page where user checks boxes and can check from 0 to 20. See edit to question above for how the data is coming
0

This is perfect when col1 is of varchar datatype.

UPDATE tbl SET col1=CASE WHEN id=1 then 1,
                         WHEN id=2 then 0,
                         when id=3 then 1 END  WHERE id IN (1,2,3)

4 Comments

I think all 3 id's (1,2,3) will have same values "1,0,1". It won't automatically match up with each id's.
Output will be "1,0,1" for all updating records
I want it to set different boolean values depending on user input of 0 or 1 etc. Data type of col1 is tinyint(1)
the query string is wrong! you can't add comma after the "WHEN" statement, or it will show up mysql error! modify it to this: UPDATE tbl SET col1=CASE WHEN id=1 then 1 WHEN id=2 then 0 when id=3 then 1 END WHERE id IN (1,2,3)

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.