讓天下沒有難用的資料庫 » Mysql 中int[M]
我們在定義數字型別的資料型別的時候,往往考慮該數字型別的資料能否裝的下該欄位的最大值,如狀態位的欄位:tinyint,表的主鍵:int,或者bigint,今天在看到開發同學提交表結構設計文件中看到數值型別的欄位定義為int(255),int(20),int(2)當時一下還沒有反映過來,我們知道在mysql中數字型別用定長位元組儲存:
Column Type | Bytes On Disk |
tinyint | 1 bytes |
smallint | 2 bytes |
mediumint | 3 bytes |
int | 4 bytes |
bigint | 8 bytes |
估計他們這樣定義是想為了儲存更多範圍的資料;
那這個int[M]中M是什麼意義喃,在定義數值型資料型別的時候,可以在關鍵字括號內指定整數值(如:int(M),M的最大值為255)顯示最大顯示寬度,顯示寬度M與資料所佔用空間,數值的範圍無關。 如果在定義欄位的時候指定zerofill,那麼當數值的顯示寬度小於指定的列寬度時候,則預設補充的空格用0代替。
Zerofill: [email protected] 10:24:26>create table int_12(id int(12) zerofill);
Query OK, 0 rows affected (0.11 sec)
[email protected] 10:28:07>insert into int_12 values(1);
Query OK, 1 row affected (0.00 sec)
[email protected] 10:28:18>select * from int_12;
+————–+
| id |
+————–+
| 000000000001 |
+————–+
1 row in set (0.00 sec)
Nozerofill:
[email protected] 11:13:31>desc int_12_no;
+——-+———+——+—–+———+——-+
| Field | Type | Null | Key | Default | Extra |
+——-+———+——+—–+———+——-+
| id | int(12) | YES | | NULL | |
[email protected] 11:14:16>insert into int_12_no values(1);
Query OK, 1 row affected (0.00 sec)
[email protected] 11:14:32>select * from int_12_no;
+——+
| id |
+——+
| 1 |
+——+
1 row in set (0.00 sec)
儲存結構:
[email protected] 11:14:38>select id,hex(id) from int_12_no;
+——+———+
| id | hex(id) |
+——+———+
| 1 | 1 |
+——+———+
1 row in set (0.00 sec)
[email protected] 11:15:17>select id,hex(id) from int_12;
+————–+———+
| id | hex(id) |
+————–+———+
| 000000000001 | 1 |
+————–+———+
1 row in set (0.00 sec)
可以看到通過hex函式匯出內部的儲存結構是一樣的,所以佔用的空間大小是相同的;
數值範圍:
[email protected] 11:17:42>create table test_4(id int(4) zerofill);
Query OK, 0 rows affected (0.12 sec)
[email protected] 11:18:17>insert into test_4 values(12345);
Query OK, 1 row affected (0.00 sec)
[email protected] 11:18:29>select * from test_4;
+——-+
| id |
+——-+
| 12345 |
+——-+
1 row in set (0.00 sec)
可以看到,當數值的範圍超過指定顯示範圍後,並沒有出現截斷的情況。