[英]Update Case When, with multiple conditions
I have this table: 我有这张桌子:
CREATE TABLE IF NOT EXISTS `my_table` (
`A` int(11) NOT NULL,
`B` int(11) NOT NULL,
`C` varchar(50) NOT NULL,
`D` varchar(30) NOT NULL,
PRIMARY KEY (`A`,`B`,`C`)
)
I want to update several entries in just one query. 我想在一个查询中更新几个条目。 I tried this: 我试过这个:
UPDATE my_table
SET D = CASE
WHEN (A = 6 AND B = 1 AND C = 'red') THEN '1#2#3#5#4'
WHEN (A = 8 AND B = 1 AND C = 'green') THEN '5#6#7#8#9'
END
But this query updates all entries in the table. 但是此查询会更新表中的所有条目。 It updates perfectly the value of 'D' of the two entries I want to update, but it also deletes the values of "D" of the other entries, and I want them to stay with their previous values. 它完全更新了我要更新的两个条目的'D'的值,但它也删除了其他条目的“D”值,我希望它们保留其先前的值。
If you do not explicitly add an else
clause to a case
expression, it implicitly acts as though you've added else null
to it. 如果没有向case
表达式显式添加else
子句,它会隐式地表示你已经为它添加了else null
。 So, your update statement is effectively equivalent to: 因此,您的更新语句实际上等效于:
UPDATE my_table
SET D = CASE
WHEN (A = 6 AND B = 1 AND C = 'red') THEN '1#2#3#5#4'
WHEN (A = 8 AND B = 1 AND C = 'green') THEN '5#6#7#8#9'
ELSE NULL
END
Which explains why you see D
being "deleted". 这解释了为什么你看到D
被“删除”了。
One way around it is to explicitly add an else
clause that simply returns D
: 解决它的一种方法是显式添加一个只返回D
的else
子句:
UPDATE my_table
SET D = CASE
WHEN (A = 6 AND B = 1 AND C = 'red') THEN '1#2#3#5#4'
WHEN (A = 8 AND B = 1 AND C = 'green') THEN '5#6#7#8#9'
ELSE D
END
Another way, which is a bit "clunkier" in syntax, but may perform slightly better, is to add a where
clause so only the relevant rows are updated: 另一种方法,在语法上有点“笨拙”,但可能稍微好一点,就是添加一个where
子句,以便只更新相关的行:
UPDATE my_table
SET D = CASE
WHEN (A = 6 AND B = 1 AND C = 'red') THEN '1#2#3#5#4'
WHEN (A = 8 AND B = 1 AND C = 'green') THEN '5#6#7#8#9'
END
WHERE (A = 6 AND B = 1 AND C = 'red') OR (A = 8 AND B = 1 AND C = 'green')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.