Declaración CASE de MySQL con tupla
Frecuentes
Visto 586 equipos
1
Tengo esta consulta:
UPDATE products_variants_relation SET
state = CASE (products_id, variants_id)
WHEN (3, 1) THEN (0)
WHEN (3, 2) THEN (4)
WHEN (3, 3) THEN (3)
WHEN (3, 4) THEN (0)
END
WHERE (products_id, variants_id) IN ((3, 1),(3, 2),(3, 3),(3, 4))
As you can probably see, I'm trying to do multiple update, because of performance. Idea is that I find the rows via combination (products_id, variants_id)
and update another field state
with correct value. I tried to remove parentheses around values behind THEN
, but then I got syntax error.
This trick for multiple update works great if there are no tuples (pairs). In this particular case, MySQL throws an error:
#1241 - Operand should contain 1 column(s)
How should I change the query so I can do multiple updates with pairs? Thanks in advance.
EDIT: Thanks to @gordon-linoff I solved it. Actually, this is also correct:
UPDATE products_variants_relation
SET state = (CASE
WHEN products_id = 3 and variants_id = 1 THEN 0
WHEN products_id = 3 and variants_id = 2 THEN 4
WHEN products_id = 3 and variants_id = 3 THEN 3
WHEN products_id = 3 and variants_id = 4 THEN 0
END)
WHERE (products_id, variants_id) IN ((3, 1),(3, 2),(3, 3),(3, 4))
So, tuples in where clause are allowed.
1 Respuestas
2
Utilice la herramienta and
y or
:
UPDATE products_variants_relation
SET state = (CASE WHEN products_id = 3 and variants_id = 1) THEN 0
WHEN products_id = 3 and variants_id = 2) THEN 4
WHEN products_id = 3 and variants_id = 3) THEN 3
WHEN products_id = 3 and variants_id = 4) THEN 0
END)
WHERE (products_id = 3 and variants_id = 1) OR
(products_id = 3 and variants_id = 2) OR
(products_id = 3 and variants_id = 3) OR
(products_id = 3 and variants_id = 4);
Neither
in
ni case
accept tuples in MySQL (see aquí).
You might find this easier to do using a join
:
UPDATE products_variants_relation pvf
(select 3 as pid, 1 as vid, 0 as val union all
select 3, 2, 4 union all
select 3, 3, 3 union all
select 3, 4, 0
) newvals
ON pvf.products_id = newvals.pid and pvf.variants_id = newvals.vid
SET pvf.state = newvals.val;
El join
does the filtering and matches the values.
contestado el 28 de mayo de 14 a las 15:05
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas mysql sql tuples case where-clause or haz tu propia pregunta.
Your first solution is ok for me, but I'm waiting, maybe someone has idea about tuples in case statement - ceruleus