简体   繁体   English

MariaDB列中仅允许使用正数

[英]Allow only positive numbers in MariaDB column

I need to ensure that the numbers inserted into a column are positive (ie greater than zero), but could not find a way to do it. 我需要确保插入到列中的数字为正(即大于零),但是找不到解决方法。 Neither decimal type's documentation nor Numeric type overview provide a solution (or a trick) that would allow me to set such a constraint on the database column. decimal类型的文档数字类型概述都没有提供允许我在数据库列上设置此类约束的解决方案(或技巧)。

I know there is the unsigned modifier, but it only says that the value may not be negative (ie less than zero) and leaves zero as a valid value for unsigned columns. 我知道有一个unsigned修饰符,但它只表示该值可能不会为 (即小于零),而将零保留为无符号列的有效值。

Is there a way to enforce this on the database schema level? 有没有办法在数据库架构级别上强制执行此操作? If not, I can trivially enforce the rule in the code, but I'd like to keep type information explicit in the schema. 如果没有,我可以在代码中轻松执行该规则,但是我想在模式中保持类型信息的明确。

MariaDB 10.2 supports CHECK constraints . MariaDB 10.2支持CHECK约束

MariaDB [test]> CREATE TABLE t1 (i INT CHECK(i>0));
Query OK, 0 rows affected (1.04 sec)

MariaDB [test]> INSERT INTO t1 VALUES (1);
Query OK, 1 row affected (0.08 sec)

MariaDB [test]> INSERT INTO t1 VALUES (0);
ERROR 4025 (23000): CONSTRAINT `i` failed for `test`.`t1`
MariaDB [test]> INSERT INTO t1 VALUES (-1);
ERROR 4025 (23000): CONSTRAINT `i` failed for `test`.`t1`
MariaDB [test]> 
MariaDB [test]> SELECT @@version;
+----------------+
| @@version      |
+----------------+
| 10.2.6-MariaDB |
+----------------+
1 row in set (0.00 sec)

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

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