MySQL中的VARCHAR和CHAR有什么区别?
我正在尝试存储MD5哈希。
MySQL中的VARCHAR和CHAR有什么区别?
我正在尝试存储MD5哈希。
当前回答
MySQL中的VARCHAR和CHAR有什么区别?
对于已经给出的答案,我想补充一点,在OLTP系统或频繁更新的系统中,即使对于可变大小的列也可以考虑使用CHAR,因为在更新期间可能会出现VARCHAR列碎片。
我正在尝试存储MD5哈希。
如果安全性真的很重要,MD5哈希并不是最好的选择。然而,如果您将使用任何哈希函数,请考虑使用BINARY类型代替它(例如,MD5将产生16字节哈希,因此BINARY(16)将足够代替CHAR(32)用于表示十六进制数字的32个字符。这将节省更多空间并提高性能。
其他回答
CHAR Vs VARCHAR
CHAR用于固定长度大小变量 VARCHAR用于可变长度大小变量。
E.g.
Create table temp
(City CHAR(10),
Street VARCHAR(10));
Insert into temp
values('Pune','Oxford');
select length(city), length(street) from temp;
输出将是
length(City) Length(street)
10 6
结论:如果变长是可变的,必须使用VARCHAR而不是CHAR来有效地利用存储空间
VARCHAR是可变长度的。
CHAR是固定长度。
如果您的内容是固定大小的,那么使用CHAR将获得更好的性能。
请参阅MySQL页面上关于CHAR和VARCHAR类型的详细解释(一定要阅读注释)。
根据高性能MySQL书:
VARCHAR stores variable-length character strings and is the most common string data type. It can require less storage space than fixed-length types, because it uses only as much space as it needs (i.e., less space is used to store shorter values). The exception is a MyISAM table created with ROW_FORMAT=FIXED, which uses a fixed amount of space on disk for each row and can thus waste space. VARCHAR helps performance because it saves space. CHAR is fixed-length: MySQL always allocates enough space for the specified number of characters. When storing a CHAR value, MySQL removes any trailing spaces. (This was also true of VARCHAR in MySQL 4.1 and older versions—CHAR and VAR CHAR were logically identical and differed only in storage format.) Values are padded with spaces as needed for comparisons.
Char有一个固定的长度(支持2000个字符),它代表字符是一种数据类型
Varchar具有可变长度(支持4000个字符)
CHAR
使用特定的内存分配 时间效率
VARCHAR
使用动态分配内存 记忆效率