mysql整數資料型別深入解析

yesye發表於2021-09-09

           此處我們給int char沒有給出他們的寬度,系統預設會給它分配一個寬度。
M指示最大顯示寬度。最大有效顯示寬度是255。顯示寬度與儲存大小或型別包含的值的範圍無關
我們來進行下試驗
複製程式碼 程式碼如下:
mysql(root@localhost:test 03:19:00)>create table c (
-> id int not null,
-> name char not null);
Query OK, 0 rows affected (0.25 sec)
mysql(root@localhost:test 03:19:34)>desc c;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id | int(11) | NO | | NULL | |
| name | char(1) | NO | | NULL | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

那麼我們可以看到這裡,系統會自動為我們的資料型別給出一個預設的寬頻值,這裡這個寬度值其實只有在zerofill的作用下才能起到一定的作用。在下面我們看下其他的預設值是多少,
複製程式碼 程式碼如下:
mysql(root@localhost:test 03:34:53)>alter table c modify id smallint;
Query OK, 0 rows affected (0.05 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql(root@localhost:test 03:39:39)>desc c;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | smallint(6) | YES | | NULL | |
| name | varchar(10) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
mysql(root@localhost:test 03:39:44)>alter table c modify id bigint;
Query OK, 4 rows affected (0.23 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql(root@localhost:test 03:40:12)>desc c;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | bigint(20) | YES | | NULL | |
| name | varchar(10) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

這裡我們再來看下當插入值大於資料型別的取值範圍的情況:
複製程式碼 程式碼如下:
mysql(root@localhost:test 03:25:58)>insert into c values(300,'chen');
Query OK, 1 row affected, 2 warnings (0.08 sec)
mysql(root@localhost:test 03:26:20)>show warnings;
+---------+------+---------------------------------------------+
| Level | Code | Message |
+---------+------+---------------------------------------------+
| Warning | 1264 | Out of range value for column 'id' at row 1 |
| Warning | 1265 | Data truncated for column 'name' at row 1 |
+---------+------+---------------------------------------------+
2 rows in set (0.00 sec)
mysql(root@localhost:test 03:26:27)>select * from c;
+------+------+
| id | name |
+------+------+
| 127 | c |
+------+------+
1 row in set (0.02 sec)
mysql(root@localhost:test 03:26:40)>insert into c values(320,'chen');
Query OK, 1 row affected, 2 warnings (0.05 sec)
mysql(root@localhost:test 03:26:53)>select * from c;
+------+------+
| id | name |
+------+------+
| 127 | c |
| 127 | c |
+------+------+
2 rows in set (0.00 sec)

這裡的tinyint是佔有一個位元組,就是可以表示從0-255這個範圍的整數,可是這裡為什麼直到127呢,原因是我們沒有給他設定無符號型別的。
                            

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/2041/viewspace-2804363/,如需轉載,請註明出處,否則將追究法律責任。

相關文章