防止在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)
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下