MySQL中的VARCHAR和CHAR有什么区别?
我正在尝试存储MD5哈希。
MySQL中的VARCHAR和CHAR有什么区别?
我正在尝试存储MD5哈希。
当前回答
根据高性能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是固定长度,VARCHAR是可变长度。CHAR总是对每个条目使用相同数量的存储空间,而VARCHAR只使用存储实际文本所需的空间。
一个CHAR(x)列只能有x个字符。 一个VARCHAR(x)列最多可以有x个字符。
由于你的MD5哈希值总是相同的大小,你可能应该使用CHAR。
然而,你不应该首先使用MD5;它的弱点是众所周知的。 请改用SHA2。 如果要对密码进行哈希,则应该使用bcrypt。
CHAR是一个固定长度的字段;VARCHAR是一个变长字段。如果您存储的字符串长度变化很大,例如名称,则使用VARCHAR,如果长度总是相同,则使用CHAR,因为它的大小效率略高,也略快。
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来有效地利用存储空间
根据高性能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.