0

I want to change different column values of a table in one query, is that possible?

I tried something like this (just a guess):

<?php
$q="UPDATE tab SET name='samit' WHERE id='1' && set name='anju' where id='4'";
$run=mysql_query($q);
if($run){
echo 'updated';
}
else{
echo 'update failed';
}
?>

It's not working. I can do this using a loop, but a loop will increase operation time.

4 Answers 4

2

You can also use JOIN

UPDATE tab t1 JOIN tab t2
    ON t1.id = 1 AND t2.id = 4
   SET t1.name = 'samit',
       t2.name = 'anju'

Here is SQLFiddle demo

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

Comments

2

You can, but you'll have to use case like so:

UPDATE tab
    SET name = CASE id
        WHEN 1 THEN 'samit'
        WHEN 4 THEN 'anju'
    END
    WHERE id IN (1,4);

Still, i'd recommend against it and just run your queries with a loop; also, mysql_* is deprecated.

Comments

1

It's propably not the best way but:

UPDATE tab
SET
name= IF(id='1', 'samit', name),
name= IF(id='4', 'anju', name)

Comments

0
UPDATE `tab`
IF(id= 1, "SET name= 'samit'", ''),
IF(id= 4, "SET name= 'anju'", '')

I hope this would work for you. Although i have not tested it yet but you can use if condition in update query

Comments

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.