MySQL中数据类型的验证

2019-01-04 15:12:16王冬梅

确实,datetime占了5个字节。

TEXT,BLOB

mysql> create table t1(name text(255)); Query OK, 0 rows affected (0.01 sec) mysql> create table t2(name text(256)); Query OK, 0 rows affected (0.01 sec) mysql> show create table t1G *************************** 1. row *************************** Table: t1 Create Table: CREATE TABLE `t1` ( `name` tinytext ) ENGINE=InnoDB DEFAULT CHARSET=latin1 1 row in set (0.00 sec) mysql> show create table t2G *************************** 1. row *************************** Table: t2 Create Table: CREATE TABLE `t2` ( `name` text ) ENGINE=InnoDB DEFAULT CHARSET=latin1 1 row in set (0.00 sec)

通过上面的输出可以看出text可以定义长度,如果范围小于28(即256)则为tinytext,如果范围小于216(即65536),则为text, 如果小于224,为mediumtext,小于232,为longtext。

上述范围均是字节数。

如果定义的是utf8字符集,对于text,实际上只能插入21845个字符

mysql> create table t1(name text) default charset=utf8; Query OK, 0 rows affected (0.01 sec) mysql> insert into t1 values(repeat('整',21846)); ERROR 1406 (22001): Data too long for column 'name' at row 1 mysql> insert into t1 values(repeat('整',21845)); Query OK, 1 row affected (0.05 sec)

DECIMAl

关于Decimal,官方的说法有点绕,

Values for DECIMAL (and NUMERIC) columns are represented using a binary format that packs nine decimal (base 10) digits into four bytes. Storage for the integer and fractional parts of each value are determined separately. Each multiple of nine digits requires four bytes, and the “leftover” digits require some fraction of four bytes. The storage required for excess digits is given by the following table.

还提供了一张对应表

对于以上这段话的解读,有以下几点:

1. 每9位需要4个字节,剩下的位数所需的空间如上所示。

2. 整数部分和小数部分是分开计算的。

譬如 Decimal(6,5),从定义可以看出,整数占1位,整数占5位,所以一共占用1+3=4个字节。

如何验证呢?可通过InnoDB Table Monitor

如何启动InnoDB Table Monitor,可参考:http://dev.mysql.com/doc/refman/5.7/en/innodb-enabling-monitors.html

mysql> create table t2(id decimal(6,5)); Query OK, 0 rows affected (0.01 sec) mysql> create table t3(id decimal(9,0)); Query OK, 0 rows affected (0.01 sec) mysql> create table t4(id decimal(8,3)); Query OK, 0 rows affected (0.01 sec) mysql> CREATE TABLE innodb_table_monitor (a INT) ENGINE=INNODB; Query OK, 0 rows affected, 1 warning (0.01 sec)

结果会输出到错误日志中。