mysql的VACHAR的最大長度究竟是多少

今天羣裏有人問:mysql

varchar 不是最大應該只能夠設置65532(第一個字節+兩個長度字節)嗎 ,可是爲何能夠設置成65533

之前一直都認爲有兩個字節來記錄長度(長度小也能夠用一個字節記錄),因此這個問題當時以爲就挺無聊的

不事後來羣裏有人給瞭解釋,忽然才發現原來事情不是這麼簡單sql

MYSQL COMPACT格式,每條記錄有一個字節來表示NULL字段分佈,若是表中有字段容許爲空,則最大隻能定到65532,若是沒有字段容許爲空,則那個字節能夠節省,最大能夠定義到65533,不知道是否是這個緣由

因而上網看了些資料,又在本地作了些實驗,原來vachar的最大長度真的是不定的(根據是否有非空字段來決定)

在本地作了下實驗,innodb+latin的環境shell

-- success
drop table if exists test;
create table test(name varchar(65533) not null)engine=innodb DEFAULT CHARSET=latin1

-- too large
drop table if exists test;
create table test(name varchar(65533))engine=innodb DEFAULT CHARSET=latin1

對於第二種狀況,容許空字段的時候是不能加到65533的長度的,最大隻能到65532,到底應該是引文的那種說法。

網上也有人作了相似的實驗,參考http://stackoverflow.com/questions/8295131/best-practise-for-sql-varchar-column-lengthcode

name varchar(100) not null will be 1 byte (length) + up to 100 chars (latin1)

name varchar(500) not null will be 2 bytes (length) + up to 500 chars (latin1)

name varchar(65533) not null will be 2 bytes (length) + up to 65533 chars (latin1)

name varchar(65532) will be 2 bytes (length) + up to 65532 chars (latin1) + 1 null byte

總結一下,原來mysql的vachar字段的類型雖然最大長度是65535,可是並非能存這麼多數據,最大能夠到65533(不容許非空字段的時候),當容許非空字段的時候只能到65532,。get

相關文章
相關標籤/搜索