???? 使用 MySQL 这么长时间了,经常使用的情况时,除了自增主键和日期时间之外 ,能 Varchar 的基本上都给 Varchar 了。团队内部还出现过 VARCHAR(2)、VARCHAT(4)、…、VARCHAT(2^N) 的情况,现在看来确实有点搞笑。
数据类型
数值类型
整数:tinyint、smallint、mediumint、int、bigint
小数:float、double、real、decimal
日期和时间类型:date、time、datetime、timestamp、year
字符串类型
字符串:char、varchat
大文本:tinytext、text、mediumtext、longtext
其他:enum、set
二进制类型:tinyblob、blob、mediumblob、longblob
空间数据类型:geometry、geometrycollection、point、linestring
JSON 数据类型
DECIMAL 范围
这里我复制一下官方文档的解释:
The declaration syntax for a DECIMAL column is DECIMAL(M,D). The ranges of values for the arguments are as follows: M is the maximum number of digits (the precision). It has a range of 1 to 65. D is the number of digits to the right of the decimal point (the scale). It has a range of 0 to 30 and must be no larger than M. If D is omitted, the default is 0. If M is omitted, the default is 10.
高精度的数据类型,常用来存储交易相关的数据
decimal(M, D) 解释:M 代表总精度(小数点前后数字总个数),D 代表刻度(小数点后的位数)。比如:decimal(5, 2) 表示存储范围为 -999.99~999.99
decimal(M, D) 范围:1<= M <= 65、0 <= D <= 30
如果省略 D,默认值是 0。如果省略 M,默认值是 10
存储空间变长(M+2 bytes)
包含两位数年份值的日期是模糊的,因为世纪是未知的。MySQL 使用这些规则解释两位数的年值:
00~69 范围内的年份值被转换为 2000~2069
70~99 范围内的年份值被转换为 1970~1999
关于 char(M)、varchar(M) 和 text 的问题:
char(M) 和 varchar(M) 中 M 代表 字符个数,并不是字节个数。当使用 UTF-8 时意味着可以插入 M 个字符,但实际会占用 M*3 个字节
char(M) 不管实际值都会占用 M 个字符的空间,页 varchar(M) 只会占用实际字符应该占用的空间 +1,并且实际空间为 +1 <= M
超过 char(M) 和 varchar(M) 的 M 设置后,字符串会被截断
char 的上限为 255 字符,varchar 和 text 的上限 65535 字符
char 在存储的时候会截断尾部的空格,varchar 和 text 不会
varchar 会使用 1~3 个字节来存储长度,而 text 不会
如上所述:
char 存定长,速度快,存在空间浪费的可能,会处理尾部空格,上限 255
varchar 存变长,速度慢,不存在空间浪费,不处理尾部空格,上限 65535,但是有存储长度实际 65532 最大可用
text,存变长大数据,速度慢,不存在空间浪费,不处理尾部空格,上限 65535,会用额外空间存放数据长度,因此可以全部使用 65535