# 数值型
# 整数型
| 数据类型 | 字节 | 备注 |
|---|---|---|
| TINYINT | 1 | |
| SMALLINT | 2 | |
| MEDIUMINT | 3 | |
| INT | 4 | |
| BIGINT | 8 | |
| BOOL,BOOLEAN | 1 | 等价于TINYINT(1) |
# 浮点型
| 数据类型 | 字节 | 备注 |
|---|---|---|
| FLOAT[(M,D)] | 4 | M表示总长度,D表示小数位数 |
| DOUBLE[(M,D)] | 8 | |
| DECIMAL[(M,D)] | M+2 | 内部以字符串形式存储数值 |
FLOAT和DOUBLE会产生误差,DECIMAL则不会
# 字符串类型
| 数据类型 | 字节 | 备注 |
|---|---|---|
| CHAR(M) | M | 0<=M<=255 |
| VARCHAR(M) | L+1 (字符串长度+1) | 0<=M<=65535 |
| TINYTEXT | L+1 | |
| TEXT | L+2 | |
| MEDIUMTEXT | L+3 | |
| LONGTEXT | L+4 | |
| ENUM('value1','value2',...) | 1或2个字节 | 枚举 |
| SET('value1', 'value2',...) | 1、2、3、4或8个字节 | 集合 |
CHAR效率高于VARCHAR,CHAR相当于拿空间换时间,VARCHAR拿时间换空间
CHAR默认存储数据的时候,后面会用空格填充到指定长度,而在检索的时候会去掉后面空格;VARCHAR在保存的时候不进行填充,尾部的空格会留下
TEXT列不能有默认值,检索的时候不存在大小写转换(区分大小写
ENUM和SET存储的是编号,编号从1开始
ENUM和SET忽略值的空格
# 日期时间类型
| 数据类型 | 字节 | 备注 |
|---|---|---|
| TIME | 3 | -838:59:59 - 838:59:59 |
| DATE | 3 | 1000-01-01 - 9999-12-31 |
| DATETIME | 8 | 1000-01-01 00:00:00 - 9999-12-31 23:59:59 |
| TIMESTAMP | 4 | 1970-01-01 00:00:01 UTC - 2038-01-19 03:14:07 |
| YEAR | 1 | 1901-2155 |
# 类型测试
# 测试ENUM
CREATE TABLE test_enum(
sex ENUM('男', '女', '保密')
);
INSERT test_enum(sex) VALUES('男');
INSERT test_enum(sex) VALUES(NULL);
INSERT test_enum(sex) VALUES(1);
# 测试SET
CREATE TABLE test_set(
a SET('A', 'B', 'C', 'D', 'E', 'F')
);
INSERT test_set(a) VALUES('A');
INSERT test_set(a) VALUES('C');
INSERT test_set(a) VALUES('C,D,E');
INSERT test_set(a) VALUES('C,F,A');
# 测试TIME
CREATE TABLE test_time(
a TIME
);
-- [D] HH:MM:SS D表示天数
INSERT test_time(a) VALUES('12:23:45');
INSERT test_time(a) VALUES('2 12:23:45');
INSERT test_time(a) VALUES('22:22');
INSERT test_time(a) VALUES('22');
INSERT test_time(a) VALUES('2 22');
-- HHMMSS
INSERT test_time(a) VALUES('121212');
INSERT test_time(a) VALUES('0');
INSERT test_time(a) VALUES(0);
INSERT test_time(a) VALUES(NOW());
INSERT test_time(a) VALUES(CURRENT_TIME);
# 测试DATE
-- YYYY-MM-DD YYYYMMDD
CREATE TABLE test_date(
a DATE
);
INSERT test_date(a) VALUES('2017-03-04');
INSERT test_date(a) VALUES('2017-2-13');
INSERT test_date(a) VALUES('4007-03-23');
INSERT test_date(a) VALUES('40071212');
INSERT test_date(a) VALUES('4007@12@12');
INSERT test_date(a) VALUES('4007.12.12');
INSERT test_date(a) VALUES('4007#12#12');
-- YY-MM-DD YYMMDD
-- YY 70-99 转换为1970-1999 00-69 2000-2069
INSERT test_date(a) VALUES('780902');
INSERT test_date(a) VALUES(NOW());
INSERT test_date(a) VALUES(CURRENT_DATE;
# 测试DATETIME
create TABLE test_datetime(
a DATETIME
);
INSERT test_datetime(a) VALUES('1004-09-12 13:24:56');
INSERT test_datetime(a) VALUES('720305121212');
INSERT test_datetime(a) VALUES(NOW());
# 测试TIMESTAMP
CREATE TABLE test_timestamp(
a TIMESTAMP
);
INSERT test_timestamp(a) VALUES('1978-10-23 12:12:12');
-- 插入CURRENT_TIMESTAMP,NULL或者什么也不写,得到当前系统时间
INSERT test_timestamp(a) VALUES(CURRENT_TIMESTAMP);
INSERT test_timestamp(a) VALUES(NULL);
INSERT test_timestamp(a) VALUES();
# 测试YEAR
CREATE TABLE test_year(
a YEAR
);
INSERT test_year(a) VALUES(1901);