• Enum枚举类型是字符串类型,其值是从事先指定的一系列值中选出,适用在某列的取值范围已经固定
• 主要好处为MySQL在存储此类数据时,直接转化成数字存储而不是字符串,可以节省空间,并且在表的.frm文件中存储“数字-字符串”之间的对应关系
mysql> CREATE TABLE shirts (
-> name VARCHAR(40),
-> size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
-> );
Query OK, 0 rows affected (0.14 sec)
mysql> insert into shirts values('a','x-small');
Query OK, 1 row affected (0.05 sec)
mysql> select * from shirts;
+------+---------+
| name | size |
+------+---------+
| a | x-small |
+------+---------+
1 row in set (0.00 sec)
mysql> insert into shirts values('a','x-small2');
ERROR 1265 (01000): Data truncated for column 'size' at row 1
mysql> select * from shirts;
+------+---------+
| name | size |
+------+---------+
| a | x-small |
+------+---------+
1 row in set (0.01 sec)
mysql> truncate table shirts;
Query OK, 0 rows affected (0.26 sec)
mysql> INSERT INTO shirts (name, size) VALUES ('dress shirt','large'), ('t-shirt','medium'),
-> ('polo shirt','small');
Query OK, 3 rows affected (0.04 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from shirts;
+-------------+--------+
| name | size |
+-------------+--------+
| dress shirt | large |
| t-shirt | medium |
| polo shirt | small |
+-------------+--------+
3 rows in set (0.00 sec)
mysql> create table temp2(size varchar(10));
ERROR 1050 (42S01): Table 'temp2' already exists
mysql> drop table temp2;
Query OK, 0 rows affected (0.14 sec)
mysql> create table temp2(size varchar(10),size varchar(10));
ERROR 1060 (42S21): Duplicate column name 'size'
mysql> create table temp2(name varchar(10),size varchar(10));
Query OK, 0 rows affected (0.16 sec)
mysql> alter table temp2 modify name varchar(20);
Query OK, 0 rows affected (0.14 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> insert into temp2 values('dress shirt','large'), ('t-shirt','medium'), ('polo shirt',,'small');
Query OK, 3 rows affected (0.08 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from temp2;
+-------------+--------+
| name | size |
+-------------+--------+
| dress shirt | large |
| t-shirt | medium |
| polo shirt | small |
+-------------+--------+
3 rows in set (0.00 sec)
mysql> desc temp2;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| name | varchar(20) | YES | | NULL | |
| size | varchar(10) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.01 sec)
mysql> select * from temp2 order by size;
+-------------+--------+
| name | size |
+-------------+--------+
| dress shirt | large |
| t-shirt | medium |
| polo shirt | small |
+-------------+--------+
3 rows in set (0.00 sec)
mysql> select * from shirts order by size;
+-------------+--------+
| name | size |
+-------------+--------+
| polo shirt | small |
| t-shirt | medium |
| dress shirt | large |
+-------------+--------+
3 rows in set (0.00 sec)