MySQL 資料類型中的 integer types 有點奇怪。你可能會見到諸如:int(3)、int(4)、int(8) 之類的 int 資料類型。剛接觸 MySQL 的時候,我還以為 int(3) 佔用的儲存空間比 int(4) 要小, int(4) 佔用的儲存空間比 int(8) 小。
後來,參看 MySQL 手冊,發現自己理解錯了。
| 代碼如下 |
複製代碼 |
int(M): M indicates the maximum display width for integer types. |
在 integer 資料類型中,M 表示最大顯示寬度。
原來,在 int(M) 中,M 的值跟 int(M) 所佔多少儲存空間並無任何關係。 int(3)、int(4)、int(8) 在磁碟上都是佔用 4 btyes 的儲存空間。說白了,除了顯示給使用者的方式有點不同外,int(M) 跟 int 資料類型是相同的。
另外,int(M) 只有跟 zerofill 結合起來,才能使我們清楚的看到不同之處。
| 代碼如下 |
複製代碼 |
mysql> drop table if exists t; mysql> create table t(id int zerofill); mysql> insert into t(id) values(10); mysql> select * from t; +------------+ | id | +------------+ | 0000000010 | +------------+ mysql> alter table t change column id id int(3) zerofill; mysql> select * from t; +------+ | id | +------+ | 010 | +------+ mysql> mysql> alter table t change column id id int(4) zerofill; mysql> select * from t; +------+ | id | +------+ | 0010 | +------+ mysql> mysql> insert into t(id) values(1000000); mysql> select * from t; +---------+ | id | +---------+ | 0010 | | 1000000 | +---------+ |
從上面的測試可以看出,“(M)”指定了 int 型數值顯示的寬度,如果欄位資料類型是 int(4),則:當顯示數值 10 時,在左邊要補上 “00”;當顯示數值 100 是,在左邊要補上“0”;當顯示數值 1000000 時,已經超過了指定寬度“(4)”,因此按原樣輸出。
在使用 MySQL 資料類型中的整數類型(tinyint、smallint、 mediumint、 int/integer、bigint)時,非特殊需求下,在資料類型後加個“(M)”,我想不出有何意義。
下面補充一下資料類型
1、整型
| MySQL資料類型 |
含義(有符號) |
| tinyint(m) |
1個位元組 範圍(-128~127) |
| smallint(m) |
2個位元組 範圍(-32768~32767) |
| mediumint(m) |
3個位元組 範圍(-8388608~8388607) |
| int(m) |
4個位元組 範圍(-2147483648~2147483647) |
| bigint(m) |
8個位元組 範圍(+-9.22*10的18次方) |
取值範圍如果加了unsigned,則最大值翻倍,如tinyint unsigned的取值範圍為(0~256)。
int(m)裡的m是表示SELECT查詢結果集中的顯示寬度,並不影響實際的取值範圍,沒有影響到顯示的寬度,不知道這個m有什麼用。
2、浮點型(float和double)
| MySQL資料類型 |
含義 |
| float(m,d) |
單精確度浮點型 8位精度(4位元組) m總個數,d小數位 |
| double(m,d) |
雙精確度浮點型 16位精度(8位元組) m總個數,d小數位 |
設一個欄位定義為float(5,3),如果插入一個數123.45678,實際資料庫裡存的是123.457,但總個數還以實際為準,即6位。
3、定點數
浮點型在資料庫中存放的是近似值,而定點類型在資料庫中存放的是精確值。
decimal(m,d) 參數m<65 是總個數,d<30且 d<m 是小數位。
4、字串(char,varchar,_text)
| MySQL資料類型 |
含義 |
| char(n) |
固定長度,最多255個字元 |
| varchar(n) |
固定長度,最多65535個字元 |
| tinytext |
可變長度,最多255個字元 |
| text |
可變長度,最多65535個字元 |
| mediumtext |
可變長度,最多2的24次方-1個字元 |
| longtext |
可變長度,最多2的32次方-1個字元 |