在MySQL建表時,遇到一個奇怪的現象:
root@localhost : test 10:30:54>CREATE TABLE tb_test ( -> recordid varchar(32) NOT NULL, -> areaShow varchar(10000) DEFAULT NULL, -> areaShow1 varchar(10000) DEFAULT NULL, -> areaShow2 varchar(10000) DEFAULT NULL, -> PRIMARY KEY (recordid) -> ) ENGINE=INNODB DEFAULT CHARSET=utf8; ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. You have to change some columns to TEXT or BLOBs 報錯
root@localhost : test 10:31:01>CREATE TABLE tb_test ( -> recordid varchar(32) NOT NULL, -> areaShow varchar(30000) DEFAULT NULL, -> areaShow1 varchar(30000) DEFAULT NULL, -> areaShow2 varchar(30000) DEFAULT NULL, -> PRIMARY KEY (recordid) -> ) ENGINE=INNODB DEFAULT CHARSET=utf8; Query OK, 0 rows affected, 3 warnings (0.26 sec) 可以建立,只是類型被轉換了。
root@localhost : test 10:31:14>show warnings; +-------+------+----------------------------------------------------+ | Level | Code | Message | +-------+------+----------------------------------------------------+ | Note | 1246 | Converting column 'areaShow' from VARCHAR to TEXT | | Note | 1246 | Converting column 'areaShow1' from VARCHAR to TEXT | | Note | 1246 | Converting column 'areaShow2' from VARCHAR to TEXT | +-------+------+----------------------------------------------------+ 3 rows in set (0.00 sec)
疑問:
為什么字段小(10000)的反而報錯,而大(30000)的則可以建立。為什么小的不能直接轉換呢?
解決:
這里多感謝orczhou的幫助,原來MySQL在建表的時候有個限制:MySQL要求一個行的定義長度不能超過65535。具體的原因可以看:
http://dev.mysql.com/doc/refman/5.1/en/silent-column-changes.html
(1)單個字段如果大於65535,則轉換為TEXT 。
(2)單行最大限制為65535,這里不包括TEXT、BLOB。
按照上面總結的限制,來解釋出現的現象:
第一個情況是:
單個字段長度:varchar(10000) ,字節數:10000*3(utf8)+(1 or 2) = 30000 ,小於65535,可以建立。
單行記錄長度:varchar(10000)*3,字節數:30000*3(utf8)+(1 or 2) = 90000,大於65535,不能建立,所以報錯:
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. You have to change some columns to TEXT or BLOBs
第二個情況是:
單個字段長度:varchar(30000) ,字節數:30000*3+(1 or 2) = 90000 , 大於65535,需要轉換成TEXT,才可以建立。所以報warnings。
單行記錄長度:varchar(30000)*3,因為每個字段都被轉換成了TEXT,而TEXT沒有限制,所以可以建立表。
root@localhost : test 10:31:14>show warnings; +-------+------+----------------------------------------------------+ | Level | Code | Message | +-------+------+----------------------------------------------------+ | Note | 1246 | Converting column 'areaShow' from VARCHAR to TEXT | | Note | 1246 | Converting column 'areaShow1' from VARCHAR to TEXT | | Note | 1246 | Converting column 'areaShow2' from VARCHAR to TEXT | +-------+------+----------------------------------------------------+
更多的信息見:MySQL中varchar最大長度是多少?