MySQL CASE...WHERE...THEN 语句
我有一个使用 CASE 子句的 MySQL UPDATE 语句
UPDATE partsList SET quantity =
CASE
WHEN partFK = 1 THEN 4
WHEN partFK = 2 THEN 8
END
WHERE buildFK = 1;
上面的语句有效。然而,当我删除其中一个 WHEN 语句时,它会中断,并且错误表明 CASE 子句没有返回任何内容。 CASE 子句必须有多个 WHEN 才能发挥作用吗?
我事先不知道需要多少更新,因此我尝试构建一个可以处理一个或多个更新的单个更新语句。
感谢您提供的任何见解。
I have a MySQL UPDATE statement that uses a CASE clause
UPDATE partsList SET quantity =
CASE
WHEN partFK = 1 THEN 4
WHEN partFK = 2 THEN 8
END
WHERE buildFK = 1;
The above statement works. Yet when I remove one of the WHEN statements, it breaks and the error indicates the CASE clause isn't returning anything. Is it that the CASE clause must have more than one WHEN to function.
I don't know beforehand how many updates I'll need, so I'm trying to build a single update statement that can handle one or many updates.
Thanks for any insights you can provide.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
并不是说
CASE
必须有多个WHEN...THEN
,而是它必须处理您提供给它的所有数据。如果删除其中一项条款,就会留下一个漏洞。例如
,对于此更新语句,如果
parkFK
为2,则更新失败,因为CASE 无法处理输入。您可以通过在 where 子句中添加另一行来限制源数据(例如
AND partFK in (1,2)
),或者您可以将ELSE
添加到案例表达。但是,根据您所显示的 SQL 语句,可能有更好的方法。据推测,partFK 是某个其他表的外键。您可以从那里提取
quantity
的值吗?It isn't that the
CASE
must have more than one,WHEN...THEN
, it's that it must handle all the data you give it.If you removed one of the clauses, you leave a hole. e.g.
With this update statement, if
parkFK
is 2, then the update fails because the CASE can't handle the input.You can either limit your source data by adding another line to your where-clause (e.g.
AND partFK in (1,2)
), or you could add anELSE
to the case expression.However, based on the SQL statement you've shown, there is probably a better way. Presumably, partFK is a foreign-key to some other table. Can you pull the value for
quantity
from there?在案例的
END
之前添加ELSE NULL
或其他内容。请参阅http://dev.mysql.com/doc/refman/ 5.0/en/case-statement.html 了解更多信息。Add
ELSE NULL
or something before theEND
of the case. See http://dev.mysql.com/doc/refman/5.0/en/case-statement.html for more info.MS SQL Server版本的sql语句如下:
MS SQL Server version of sql statement would be as following: