MySQL字段值,可以定义超出位数的浮点数吗?

发布于 2024-08-04 23:34:20 字数 311 浏览 0 评论 0原文

三个问题,基本相同:

所以我的表有一个字段,它的数据类型是float。然而,只有 64 个可能的值,范围从 0.25 到 16.0(增量为 0.25),并且我只想允许这些值作为额外的验证层。

  1. 我可以将该字段设置为大于零吗?

  2. 我可以为浮点字段设置最小值和最大值吗?

  3. 我可以以某种方式设置增量吗?

或者,我应该考虑:

a)将其设置为整数,并在输入之前将任何输入乘以 4,并将最大值设置为 64。b

)使用非常长的枚举?

Three questions, all basically the same:

So my table has a field, and it's data type is float. There are only 64 possible values, however, ranging from 0.25 to 16.0 (increments of 0.25), and I'd like to only allow those values as an extra layer of validation.

  1. Can I set the field to be greater than zero?

  2. Can I set a minimum and maximum value for a float field?

  3. Can I set the increments in some way?

Or, should I consider:

a) setting it as an integer and multiplying any input by 4 before it goes in, and setting a maximum value of 64.

b) using a really long enum?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

栖竹 2024-08-11 23:34:20

这通常是通过检查约束来完成的。不幸的是 MySql 不支持 CHECK CONSTRAINT。您可以使用 BEFORE UPDATE TRIGGER 代替...

CREATE TRIGGER t BEFORE UPDATE ON yourTable 
FOR EACH ROW BEGIN 
IF NEW.name --here you put a check for a valid value
   SET NEW.name = 1 / 0;      --an error is raised - no insert
END IF; 

This is usually done with a CHECK CONSTRAINT. Unfortunately MySql doesn't support CHECK CONSTRAINT. You can use BEFORE UPDATE TRIGGER instead...

CREATE TRIGGER t BEFORE UPDATE ON yourTable 
FOR EACH ROW BEGIN 
IF NEW.name --here you put a check for a valid value
   SET NEW.name = 1 / 0;      --an error is raised - no insert
END IF; 
热情消退 2024-08-11 23:34:20

通常这种事情是在客户端应用程序中强制执行的。但是,如果您搜索 mysql 的“服务器强制数据完整性”,您会找到一些您需要的内容。

Typically this sort of thing is enforced in the client application. However, if you search for "server-enforced data integrity" for mysql you'll find some of what you need.

独自唱情﹋歌 2024-08-11 23:34:20

我个人会使用 DECIMAL,而不是 FLOAT。 FLOAT 只是您的价值的近似值,您的价值确实是具体的。

为了强制执行特定值,我将创建一个仅包含这 64 个值的查找表并使用外键。

i personally would use DECIMAL, not FLOAT. FLOAT is only an approximation of your value, and your values are really specific.

to enforce specific values, i would create a lookup table with just those 64 values in there and use a foreign key.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文