如何防止 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)

更新於:2019 年 7 月 30 日

2K+ 次檢視

開啟你的 職業生涯

透過完成課程來獲得認證

開始
廣告