100
c
字节的磁盘空间,其中c
是存储字符串的长度.100
M
个字符M
必须介于1和65535之间c
bytes (for M
≤ 255) or 2 + c
(for 256 ≤ M
≤ 65535) bytes of disk space where c
is the length of the stored stringTEXT
has a fixed max size of 2¹⁶-1 = 65535
characters.
VARCHAR
has a variable max size M
up to M = 2¹⁶-1
.
So you cannot choose the size of TEXT
but you can for a VARCHAR
.
另一个区别是,不能在TEXT
列上放置索引(全文索引除外)
但是,如果您知道可能输入字符串的最大长度只有M
,例如电话号码、姓名或类似的内容,那么您也希望使用VARCHAR
.然后,你可以使用VARCHAR(30)
而不是TINYTEXT
或TEXT
,如果有人试图在你的电话号码栏中保存所有三本《指环王》的文本,你只存储前30个字符:)
Edit:如果要存储在数据库中的文本长度超过65535个字符,则必须 Select MEDIUMTEXT
或LONGTEXT
,但要小心:MEDIUMTEXT
存储最多16MB的字符串,LONGTEXT
存储最多4GB的字符串.如果使用LONGTEXT
并通过PHP获取数据(至少如果使用mysqli
而不使用store_result
),可能会出现内存分配错误,因为PHP试图分配4GB内存,以确保整个字符串都可以缓冲.这可能在PHP以外的其他语言中也会发生.
但是,您应该判断输入(是否太长?是否包含奇怪的代码?)before将其存储在数据库中.
Notice: For both types, the required disk space depends only on the length of the stored string and not on the maximum length.
E.g. if you use the charset latin1 and store the text "Test" in VARCHAR(30)
, VARCHAR(100)
and TINYTEXT
, it always requires 5 bytes (1 byte to store the length of the string and 1 byte for each character). If you store the same text in a VARCHAR(2000)
or a TEXT
column, it would also require the same space, but, in this case, it would be 6 bytes (2 bytes to store the string length and 1 byte for each character).
有关更多信息,请查看documentation.
最后,我想补充一点,TEXT
和VARCHAR
都是可变长度的数据类型,因此它们很可能会最小化存储数据所需的空间.但这需要在性能上进行权衡.如果需要更好的性能,必须使用固定长度的类型,如CHAR
.你可以阅读更多关于这here的信息.