简体   繁体   English

设置MySQL字段的最小值 - 可能吗?

[英]Set minimum value of MySQL field - possible?

Quick newbie MySQL question. 快速新手MySQL问题。 What would be the simplest way to ensure that the minimum value of a given field is 0? 确保给定字段的最小值为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. 基本上,我们有一个自动运行的脚本,每隔15分钟从一个字段的值中减去一个整数值 - 但我们希望任何一个0的条目保持为0而不是负数。

This could be simply done with a loop in PHP but I'm trying to limit calls to the database... 这可以简单地用PHP中的循环来完成,但我试图限制对数据库的调用......

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? 是否有一种简单的方法可以使字段0的最小值或使其成为任何放在该字段中的负值自动变为0?

Thanks! 谢谢!

您是否尝试过一个简单的条件“WHERE”或者问题比这更复杂?

UPDATE mytable SET mycolumn=mycolumn-1 WHERE mycolumn>0

you can set UNSIGNED attribute for your field. 您可以为您的字段设置UNSIGNED属性。 mysql will generate an error if you try to set this field to something < 0. 如果您尝试将此字段设置为<0,则mysql将生成错误。

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. 更正负值,将其设置为零的更新触发器是另一个想法。

Common way to do this would be CHECK constraint but MySQL does not support that. 执行此操作的常见方法是CHECK约束,但MySQL不支持。

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. 因此,要么使列无符号和/或确保在应用程序逻辑中仅在值> 0时减去该值。

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

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