【MySQL】char和varchar的不同

来源:互联网 发布:苹果5如何用移动4g网络 编辑:程序博客网 时间:2024/06/03 12:52

CHAR和VARCHAR类型类似,但它们保存和检索的方式不同。它们的最大长度和是否尾部空格被保留等方面也不同。在存储或检索过程中不进行大小写转换。

CHAR    0-255字节 定长字符串VARCHAR 0-65535 字节  变长字符串

创建测试表

mysql> create table char_test(char_col char(10));Query OK, 0 rows affected (0.30 sec)

查看mysql中的创建语句(这样可以看到更详细的创建语句,可以把INTEGER、BOOL等别名转换为MySQL的基本数据类型。);

mysql> show create table char_test;+-----------+------------------------------------------------------------------------------------------------------+| Table     | Create Table                                                                                         |+-----------+------------------------------------------------------------------------------------------------------+| char_test | CREATE TABLE `char_test` (  `char_col` char(10) DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1 |+-----------+------------------------------------------------------------------------------------------------------+1 row in set (0.00 sec)

插入3行数据

mysql> insert into char_test(char_col) values    -> ('string1'),('  string2'),('string3  ');Query OK, 3 rows affected (0.03 sec)Records: 3  Duplicates: 0  Warnings: 0

这是后检索这些值的时候,发现string3的末尾空格被截断了;

mysql> select concat("'", char_col, "'" ) from char_test;+-----------------------------+| concat("'", char_col, "'" ) |+-----------------------------+| 'string1'                   || '  string2'                 || 'string3'                   |+-----------------------------+3 rows in set (0.00 sec)

如果用varchar(10)字段存储相同的值,可以得到如下结果:

mysql> select concat("'", varchar_col, "'" ) from varchar_test;+--------------------------------+| concat("'", varchar_col, "'" ) |+--------------------------------+| 'string1'                      || '  string2'                    || 'string3  '                    |+--------------------------------+3 rows in set (0.00 sec)

参考:高性能MySQL(第3版). Baron Schwartz,Peter Zaitsev,Vadim Tkachenko 著;宁海元,周振兴,彭立勋 等 译

原创粉丝点击