向 MySQL 中的整数列添加正整数约束?
您需要为此使用unsigned,因为它不允许您输入负数。
语法如下
CREATE TABLE yourTableName ( yourColumnName INT UNSIGNED );
为了理解这个概念,让我们创建一个表。创建表的查询如下
mysql> create table OnlyPositiveValue - > ( - > Marks int UNSIGNED - > );
在表中插入数据之前,请使用以下查询。
查询如下
mysql> SET @@SESSION.sql_mode = 'STRICT_TRANS_TABLES';
现在,如果您将在INSERT命令中添加一个负数,则会出现以下错误
mysql> insert into OnlyPositiveValue values(-10); ERROR 1264 (22003): Out of range value for column 'Marks' at row 1 mysql> insert into OnlyPositiveValue values(-100); ERROR 1264 (22003): Out of range value for column 'Marks' at row 1
让我们插入正数。
查询如下
mysql> insert into OnlyPositiveValue values(0); mysql> insert into OnlyPositiveValue values(10); mysql> insert into OnlyPositiveValue values(100);
使用select语句显示表中的所有记录。
查询如下
mysql> select *from OnlyPositiveValue;
以下是显示正数的输出
+-------+ | Marks | +-------+ | 0 | | 10 | | 100 | +-------+ 3 rows in set (0.00 sec)