如何防止 MySQL 中出现负数?
要防止 MySQL 中出现负数,你需要使用 INT UNSIGNED。假设你创建了一张表,其列为 int,即此处的 UserGameScores
mysql> create table preventNegativeNumberDemo - > ( - > UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > UserName varchar(20), - > UserGameScores int - > ); Query OK, 0 rows affected (1.74 sec)
现在,如果你需要防止该列中出现负数,请使用 INT UNSIGNED 修改同一列
mysql> alter table preventNegativeNumberDemo modify column UserGameScores INT UNSIGNED NOT NULL; Query OK, 0 rows affected (3.32 sec) Records: 0 Duplicates: 0 Warnings: 0
现在再次查看表描述。
查询如下所示
mysql> desc preventNegativeNumberDemo;
以下是输出
+----------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------------+------------------+------+-----+---------+----------------+ | UserId | int(11) | NO | PRI | NULL | auto_increment | | UserName | varchar(20) | YES | | NULL | | | UserGameScores | int(10) unsigned | NO | | NULL | | +----------------+------------------+------+-----+---------+----------------+ 3 rows in set (0.00 sec)
现在,如果你尝试为 UserGameScores 列插入负数,MySQL 会给出一个错误,因为我们已将其设置为 INT UNSIGNED。让我们插入一些值,包括负数
mysql> insert into preventNegativeNumberDemo(UserName,UserGameScores) values('Larry',0); Query OK, 1 row affected (1.20 sec) mysql> insert into preventNegativeNumberDemo(UserName,UserGameScores) values('Mike',-1); ERROR 1264 (22003): Out of range value for column 'UserGameScores' at row 1 mysql> insert into preventNegativeNumberDemo(UserName,UserGameScores) values('Sam',-100); ERROR 1264 (22003): Out of range value for column 'UserGameScores' at row 1 mysql> insert into preventNegativeNumberDemo(UserName,UserGameScores) values('John',100); Query OK, 1 row affected (0.84 sec) mysql> insert into preventNegativeNumberDemo(UserName,UserGameScores) values('Bob',200); Query OK, 1 row affected (0.48 sec)
当我们尝试插入负值时,请查看上面的错误。
现在,使用 select 语句从表中显示所有记录。只会插入正数
mysql> select *from preventNegativeNumberDemo;
以下是输出
+--------+----------+----------------+ | UserId | UserName | UserGameScores | +--------+----------+----------------+ | 1 | Larry | 0 | | 2 | John | 100 | | 3 | Bob | 200 | +--------+----------+----------------+ 3 rows in set (0.00 sec)
广告