我有这个问题:
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))
正如您可能看到的,由于性能原因,我尝试进行多次更新。我的想法是通过组合(products_id, variants_id)
找到行,并使用正确的值更新另一个字段state
。我试图删除THEN
后面的值的括号,但后来我遇到了语法错误。
如果没有元组(对),这个多次更新技巧很有用。在这种特殊情况下,MySQL会抛出错误:
#1241 - Operand should contain 1 column(s)
如何更改查询以便我可以使用对进行多次更新?提前谢谢。
修改 感谢@ gordon-linoff我解决了它。实际上,这也是正确的:
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))
因此,允许where子句中的元组。
答案 0 :(得分:2)
使用and
和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);
in
和case
都不接受MySQL中的元组(请参阅here)。
您可能会发现使用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;
join
执行过滤并匹配值。