简体   繁体   English

MySQL MAX()函数用于比较更新中的数值?

[英]MySQL MAX() function to compare numeric values in an update?

When updating a row, I want to have a built-in check to do some bounds checking. 更新行时,我希望有一个内置的检查来进行一些边界检查。 Most languages have a MAX() function to return the maximum of the arguments passed, but MySQL seems to use MAX() for something else. 大多数语言都有一个MAX()函数来返回传递的参数的最大值,但MySQL似乎使用MAX()来做其他事情。 For example: 例如:

UPDATE person SET dollars = MAX(0, dollars-20) WHERE id=1

I want to subtract 20 dollars from person id 1, but I don't want dollars to ever be represented by a negative value, so I want a built-in comparison with 0. Does this work? 我想从人id 1减去20美元,但我不希望美元永远用负值表示,所以我希望与0进行内置比较。这有用吗? Or is there another way? 或者还有另一种方式吗? Thanks! 谢谢!

MySQL supports a function called GREATEST() . MySQL支持一个名为GREATEST()的函数。 It returns the largest value among a list of its arguments. 它返回其参数列表中的最大值。

UPDATE person SET dollars = GREATEST(0, dollars-20) WHERE id=1

This isn't a standard function in ANSI SQL, so don't count on it being available in other brands of SQL database. 这不是ANSI SQL中的标准函数,因此不要指望它在其他品牌的SQL数据库中可用。 If you need a vendor-independent solution, use the CASE syntax suggested by others. 如果您需要独立于供应商的解决方案,请使用其他人建议的CASE语法。 But if all you need to use is MySQL, this function is more concise. 但如果你需要使用的只是MySQL,这个功能更简洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM