MySQL中varchar(N)和int(N)的含义及其与char区别(笔试题遇到过)

1)varchar与char的区别

  • 固定长度 (char) 或可变长度 (varchar) 字符数据类型。

Varchar存储可变长字符串,小于255字节时需要1个额外字节(大于255需要2个额外字节)存储长度,最大长度为65532字节(所有列总和);
char存储定长(right padding),读取时会截断末尾空格,长度最大为255字符;


2)varchar(30)中30的涵义
最大存储30个字符;varchar(5)和(200)存储hello所占空间一样,但后者在排序时会消耗更多内存,因为order by col采用fixed_length计算col长度(memory引擎也一样)

Data Type

Storage Required

CHAR(M)

M × w bytes, 0 <= M <= 255, where w is the number of bytes required for the maximum-length character in the character set. See<span color:#015a84;"="" style="word-wrap: break-word; font-size: 10pt;">Section 14.5.13.6, “Physical Row Structure” for information about CHARdata type storage requirements for InnoDB tables.

BINARY(M)

M bytes, 0 <= M <= 255

VARCHAR(M), VARBINARY(M)

L + 1 bytes if column values require 0 – 255 bytes, L + 2 bytes if values may require more than 255 bytes



For example, a VARCHAR(255) column can hold a string with a maximum length of 255 characters(字符而非字节). 对于latin1,’abcd’的L为4,存储需要5个字节;对于ucs2(双字节字符),则需要10个字节存储(最大长度为510>255,故需要额外2个字节)


3)int(20)中20的涵义
20表示最大显示宽度为20,但仍占4字节存储,存储范围不变;
create table int_test(a int zerofill NOT NULL auto_increment, PRIMARY KEY (a));
create table int_test_4(a int(4) zerofill NOT NULL auto_increment, PRIMARY KEY (a));

select * from int_test;
+------------+
| a          |
+------------+
| 0000000001 |
| 0000000002 |
| 0000000003 |
| 2147483648 |
+------------+

select * from int_test_4;
+------------+
| a          |
+------------+
|       0001 |
|       0002 |
|       0003 |
| 2147483648 |
+------------+

4)为什么MySQL这样设计?

对大多数应用没有意义,只是规定一些工具用来显示字符的个数;int(1)和int(20)存储和计算均一样;

此文章转载于http://blog.itpub.net/15480802/viewspace-1330966/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值