如何在 MySQL 中防止出现负数?

mysqlmysqli database更新于 2025/5/29 11:56:17

要防止 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)

相关文章


有用资源