Danny H
Danny H

Reputation: 23

MySQL - Set whichever column is equal to a value

I have ten columns called image1, image2...image10, I want to update the value of one column to a new value, but it must only update the one column which is equal to the value I supply.

For example lets the supplied value is 1, and I want to change it to a string such as "C:/folder/subfolder".

I was thinking is there some if statement such as "if image1 = 1 set image1 = "C:/folder/subfolder" else if image2 = 1 set image2 = "C:/folder/subfolder", etc?

Upvotes: 2

Views: 97

Answers (2)

Alderin
Alderin

Reputation: 150

The WHERE clause might be what you need in your SQL. Something like:

UPDATE images SET image1="C:/folder/subfolder" WHERE image1="1";

Might not be the full answer, but I thought this might help on the right path.

Upvotes: 0

Barmar
Barmar

Reputation: 780724

You can use an IF expression. If it matches the supplied value, you return the new value, otherwise you return the old value (so it has no effect on that column).

UPDATE tableName
    SET image1 = IF(image1 = '1', 'C:/folder/subfolder', image1),
        image2 = IF(image2 = '1', 'C:/folder/subfolder', image2),
        image3 = IF(image3 = '1', 'C:/folder/subfolder', image3),
        ...
WHERE '1' IN (image1, image2, image3, ...)

Upvotes: 1

Related Questions