2012-02-20 8 views
10

con MySQL Estoy usando esta consulta:MYSQL actualización del conjunto en la misma columna pero con múltiples cláusulas WHERE

UPDATE CustomerDetails_COPY 
SET Category_ID = 10 
WHERE Category_ID = 2 

que ya está bien, pero me gustaría anuncio 15+ más SET/WHERE a ella como:

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 
..... 

¿Cómo puedo agregar algo a esto?

EDIT:

de acuerdo con los cazadores Sugerencia:

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) 

Esto funciona muy bien! Gracias

Respuesta

13

Algo como esto debería funcionar para usted:

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) 

Como alternativa, como se sugiere Simon, que podría hacer esto para salvar a la entrada de los valores dos veces:

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 

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

+1

Eliminé mi comentario como probé esto y funcionó, agradable :) Como nota, podría agregar "ELSE Category_ID" antes de "END" si no desea incluir el WHERE –

+0

Gracias. Un buen punto; salvaría de ingresar las columnas dos veces. –

+2

Con la cláusula 'WHERE', se garantiza que podrá utilizar un índice en Category_ID, también con [safe-updates] (http://dev.mysql.com/doc/refman/5.0/en/ mysql-command-options.html # option_mysql_safe-updates) habilitado, debe ingresar una cláusula 'WHERE' con un' UPDATE', por lo que la cláusula 'ELSE' podría no ser la mejor opción. Quédate con 'WHERE'. –

2

La forma típica de hacer esto sería

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

¿Hay alguna razón por la que está evitando este enfoque?

¿Hay alguna correlación entre los valores nuevos y antiguos de category_ID?

+0

Tengo más de 300 diferentes tipos :( – Monty

+0

¿Por qué eso cambia nada? Esta es una consulta única, ¿verdad? Así que utiliza tu función copiar/pegar de tu computadora y haz un día de eso. A menos, por supuesto, el NUEVO valor de cualquiera de estos conflictos con el valor VIEJO de algunos. Entonces es posible que necesite una tabla temporal o la solución de Hunter – JohnFx

+0

La mayoría son diferentes, pero algunas son iguales. – Monty

1

puede crear otra tabla donde se hace la asignación ... como:

map_table 
----------- 
mani_id 
new_id 

luego rellenarlo ...

continuación

UPDATE CustomerDetails_Copy set category_id = (select new_id from map_table where mani_id = category_id) 
Cuestiones relacionadas