Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL UPDATE SET on the Same Column but with multiple WHERE Clauses

Tags:

mysql

With MYSQL I'm using this query:

UPDATE CustomerDetails_COPY
SET Category_ID = 10
WHERE Category_ID = 2

Thats fine but I'd like to ad 15+ more SET/WHERE to it like:

UPDATE CustomerDetails_COPY
SET Category_ID = 9  WHERE Category_ID = 3
SET Category_ID = 12 WHERE Category_ID = 4
SET Category_ID = 11 WHERE Category_ID = 5
.....

How would I add to this?

EDIT:

As Per Hunters Suggestion:

UPDATE CustomerDetails_COPY
    SET Category_ID = CASE Category_ID
        WHEN 2 THEN 10 
        WHEN 3 THEN 9
        WHEN 4 THEN 12
        WHEN 5 THEN 11
    END
WHERE Category_ID IN (2,3,4,5)

This works Great! Thanks

like image 959
Monty Avatar asked Feb 20 '12 21:02

Monty


People also ask

How do you update a column with multiple values?

First, specify the table name that you want to change data in the UPDATE clause. Second, assign a new value for the column that you want to update. In case you want to update data in multiple columns, each column = value pair is separated by a comma (,). Third, specify which rows you want to update in the WHERE clause.

How Update same column with different values in MySQL?

Specific columns can be modified using the SET clause by supplying new values for that column. The WHERE clause can be used to specify the conditions those identify which rows to update. Without using WHERE clause, all rows are updated. The ORDER BY clause is used to update the order that is already specified.

Can you have multiple WHERE clauses in MySQL?

Multiple WHERE Clause Conditionals Using the MySQL AND Logical Operator. Oftentimes, you need multiple filter conditionals in a WHERE clause in order to target specific rows of data.

How do you update multiple columns with multiple conditions?

To update multiple columns use the SET clause to specify additional columns. Just like with the single columns you specify a column and its new value, then another set of column and values. In this case each column is separated with a column.


1 Answers

Something like this should work for you:

UPDATE CustomerDetails_COPY
    SET Category_ID = CASE Category_ID
        WHEN 2 THEN 10 
        WHEN 3 THEN 9
        WHEN 4 THEN 12
        WHEN 5 THEN 11
    END
WHERE Category_ID IN (2,3,4,5)

Alternatively, as Simon suggested, you could do this to save from entering the values twice:

UPDATE CustomerDetails_COPY
    SET Category_ID = CASE Category_ID
        WHEN 2 THEN 10 
        WHEN 3 THEN 9
        WHEN 4 THEN 12
        WHEN 5 THEN 11
        ELSE Category_ID
    END

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

like image 79
Hunter McMillen Avatar answered Oct 20 '22 12:10

Hunter McMillen