设置 MySQL 字段的最小值 - 可能吗?
快速新手 MySQL 问题。确保给定字段的最小值为 0 的最简单方法是什么?
基本上,我们有一个自动运行的脚本,每 15 分钟从字段值中减去一个整数值,但我们希望任何达到 0 的条目都保持为 0,而不是负值。
这可以简单地通过 PHP 中的循环来完成,但我试图限制对数据库的调用...
有没有一种简单的方法可以使字段的最小值为 0 或将任何负值放入该字段自动变成0?
谢谢!
Quick newbie MySQL question. What would be the simplest way to ensure that the minimum value of a given field is 0?
Basically, we have a script that runs automatically and subtracts an integer value from the value of a field every 15 minutes--but we want any entry that gets to 0 to stay at 0 and not go negative.
This could be simply done with a loop in PHP but I'm trying to limit calls to the database...
Is there a simple way to either make the minimum value for a field 0 or make it so any negative value put in that field automatically becomes 0?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您是否尝试过简单的条件“WHERE”,或者问题比这更复杂?
Have you tried a simple conditional "WHERE" or is the problem more complex than that?
您可以为您的字段设置 UNSIGNED 属性。如果您尝试将此字段设置为 <<<,则 mysql 将生成错误。 0。
you can set UNSIGNED attribute for your field. mysql will generate an error if you try to set this field to something < 0.
您可以将逻辑添加到脚本中,以便在值已经为零时不从该值中减去...
另一个想法是更正负值的更新触发器,将它们设置为零。
You could add the logic to your script to not subtract from the value if the value is already zero...
An update trigger that corrects negative values, setting them to zero is another idea.
执行此操作的常见方法是 CHECK 约束,但 MySQL 不支持该约束。
因此,要么使该列无符号,和/或确保在您的应用程序逻辑中,仅当该值 > 时才减去该值。 0。
Common way to do this would be CHECK constraint but MySQL does not support that.
So either make the column unsigned and/or make sure that in your application logic you are subtracting the value only when it is > 0.