3

I know this question may be asked too many times on these forums but I genuinely cannot find a solid answer. They all give different methods.

Anyway, I have this code to update one row:

$sql = "UPDATE $userName SET P1 = '$p1MON' WHERE day = 'MON1'";

Is it possible to update multiple rows in the same query? Something like this:

$sql = "UPDATE $userName SET P1 = '$p1MON' WHERE day = 'MON1',
        UPDATE $userName SET P1 = '$p1TUE' WHERE day = 'TUE1',
        UPDATE $userName SET P1 = '$p1WED' WHERE day = 'WED1'";

Or, to update multiple rows in one query, do they have to share an identifier?

Thanks.

EDIT: A suggestion in the comments , doesn't seem to work...

$sql = "UPDATE $userName SET P1 = '$p1MON' WHERE day = 'MON1';
        UPDATE $userName SET P1 = '$p1TUE' WHERE day = 'TUE1';
        UPDATE $userName SET P1 = '$p1WED' WHERE day = 'WED1'";
3

3 Answers 3

10

Use a case expression:

UPDATE $userName
SET P1 = case day
         when 'MON1' then '$p1MON'
         when 'TUE1' then '$p1TUE'
         when 'WED1' then '$p1WED'
         end
where day IN ('MON1', 'TUE1', 'WED1')
Sign up to request clarification or add additional context in comments.

6 Comments

What exactly does a case expression do? I'd like to understand it.
For different day values, it returns different values. For day value 'MON1', it returns '$p1MON' etc.
Thats exactly what I was looking for and it works great. Thanks. I'll accept the answer as soon as it lets me.
Hold on - what if I wanted a different column, rather than just P1? Would I require a new query? @jarlh
|
0

is the field day a unique key field?

If so you can use on duplicate key update syntax.

INSERT INTO $userName(day, P1) VALUES
('MON1', '$p1MON'),
('TUE1', '$p1TUE'),
('WED1', '$p1WED')
ON DUPLICATE KEY UPDATE P1=VALUES(P1)

Comments

0

Depending you database engine you can try something like this

$sql = "UPDATE $userName SET P1 = '$p1MON' WHERE day = 'MON1'; UPDATE $userName SET P1 = '$p1TUE' WHERE day = 'TUE1'; UPDATE $userName SET P1 = '$p1WED' WHERE day = 'WED1'"

Or

$sql = "UPDATE $userName SET P1 = '$p1MON' WHERE day = 'MON1' go  UPDATE $userName SET P1 = '$p1TUE' WHERE day = 'TUE1' go  UPDATE $userName SET P1 = '$p1WED' WHERE day = 'WED1'"

Using ; or GO (depending of you database) separate instructions to execute then on "one 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.