[英]How can I use MySQL CASE inside SET without it being destructive?
I have many fields that I need to mass replace without destroying other data in that column.我有很多字段需要批量替换而不破坏该列中的其他数据。
If I run:如果我运行:
UPDATE ospos_items AS a
INNER JOIN ospos_items AS b ON a.item_id = b.item_id
SET a.custom7 = 'Detective Novels'
WHERE a.custom7 = 'DN'
AND a.custom3 = 'English Literature';
The Update is properly non-destructive.更新是正确的非破坏性的。 But if I run the following code in an effort to combine queries:但是,如果我运行以下代码以组合查询:
UPDATE ospos_items AS a
INNER JOIN ospos_items AS b ON a.item_id = b.item_id
SET a.custom7 = CASE
WHEN a.custom7 = 'DN' THEN 'Detective Novels'
WHEN a.custom7 = 'HF' THEN 'Historical Fiction'
WHEN a.custom7 = 'HUM' THEN 'Humor'
WHEN a.custom7 = 'NOV' THEN 'Novels'
WHEN a.custom7 = 'YA' THEN 'Young Adults'
END
WHERE a.custom3 IN('English Literature');
It sets all values in that column to NULL not found in the CASE.它将该列中的所有值设置为 CASE 中未找到的 NULL。 For example, some of the fields in that column have already been converted.例如,该列中的某些字段已被转换。 How can I make my second query non-destructive to values not found in the CASE statement?如何使我的第二个查询对 CASE 语句中未找到的值具有非破坏性?
There are two solutions:有两种解决方案:
ELSE a.custom7
to the CASE
expression.将ELSE a.custom7
添加到CASE
表达式。 Then it will keep the same value if none of the WHEN
conditions match.如果WHEN
条件都不匹配,它将保持相同的值。AND a.custom7 IN ('DN', 'HF', 'HUM', 'NOV', 'YA')
to the WHERE
clause.将AND a.custom7 IN ('DN', 'HF', 'HUM', 'NOV', 'YA')
到WHERE
子句。 Then it will only update the rows where one of the CASE
expressions matches.然后它只会更新CASE
表达式之一匹配的行。 BTW, when you're testing the same column in every WHEN
clause, you can use the simpler:顺便说一句,当您在每个WHEN
子句中测试同一列时,您可以使用更简单的:
CASE a.custom7
WHEN 'DN' THEN 'Detective Novels'
WHEN 'HF' THEN 'Historical Fiction'
...
END
You need to add an ELSE
clause to the CASE
expression so that the value remains the same when it is not one of the ones you want to change:您需要在CASE
表达式中添加一个ELSE
子句,以便该值在不是您要更改的值之一时保持不变:
UPDATE ospos_items AS a
INNER JOIN ospos_items AS b ON a.item_id = b.item_id
SET a.custom7 = CASE
WHEN a.custom7 = 'DN' THEN 'Detective Novels'
WHEN a.custom7 = 'HF' THEN 'Historical Fiction'
WHEN a.custom7 = 'HUM' THEN 'Humor'
WHEN a.custom7 = 'NOV' THEN 'Novels'
WHEN a.custom7 = 'YA' THEN 'Young Adults'
ELSE a.custom7
END
WHERE a.custom3 IN('English Literature');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.