防止在MySQL中使用负数?
为了防止MySQL中出现负数,您需要使用INTUNSIGNED。假设您创建了一个带有int列的表,即UserGameScores
mysql> create table preventNegativeNumberDemo - > ( - > UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > UserName varchar(20), - > UserGameScores int - > );
现在,如果需要防止出现负数,请使用INTUNSIGNED修改同一列
mysql> alter table preventNegativeNumberDemo modify column UserGameScores INT UNSIGNED NOT NULL; 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会给出错误信息,因为我们已将其设置为INTUNSIGNED。让我们插入一些值,包括负数
mysql> insert into preventNegativeNumberDemo(UserName,UserGameScores) values('Larry',0); 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); mysql> insert into preventNegativeNumberDemo(UserName,UserGameScores) values('Bob',200);
当我们尝试插入负值时,请看上面的错误。
现在,使用select语句显示表中的所有记录。仅插入正数
mysql> select *from preventNegativeNumberDemo;
以下是输出
+--------+----------+----------------+ | UserId | UserName | UserGameScores | +--------+----------+----------------+ | 1 | Larry | 0 | | 2 | John | 100 | | 3 | Bob | 200 | +--------+----------+----------------+ 3 rows in set (0.00 sec)