MySQL字段之集合(set)枚举(enum)
集合 SET
mysql> create table jihe(f1 set('f','m'));
Query OK, 0 rows affected (0.11 sec)
mysql> desc jihe;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| f1 | set('f','m') | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
可以插入值 "f" "m"
mysql> insert into jihe values("f");
Query OK, 1 row affected (0.56 sec)
mysql> insert into jihe values("m");
Query OK, 1 row affected (0.19 sec)
可以按照序号输入 注意序号为 1 2 4 8 16 32 ....
mysql> insert into jihe values("1");
Query OK, 1 row affected (0.11 sec)
mysql> insert into jihe values("2");
Query OK, 1 row affected (0.11 sec)
所以如果是3那插入的值为 第一个和第二个
mysql> insert into jihe values("3");
Query OK, 1 row affected (0.17 sec)
+-------+
| f1 |
+-------+
| f |
| m |
| f |
| m |
| f,m |
+-------+
其他字母不能插入
mysql> insert into jihe values("q");
ERROR 1265 (01000): Data truncated for column 'f1' at row 1
插入空
mysql> insert into jihe values("0");
Query OK, 1 row affected (0.11 sec)
超出序号之和不能插入
mysql> insert into jihe values("4");
ERROR 1265 (01000): Data truncated for column 'f1' at row 1
枚举
mysql> create table meiju(f1 enum('1','2','3','4','5','6'));
Query OK, 0 rows affected (0.92 sec)
mysql> desc meiju;
+-------+-------------------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------------------------+------+-----+---------+-------+
| f1 | enum('1','2','3','4','5','6') | YES | | NULL | |
+-------+-------------------------------+------+-----+---------+-------+
mysql> insert into meiju values(2);
mysql> insert into meiju values("2");
mysql> insert into meiju values("6");
序号为 1 2 3 4 5
内容没有序号也没有就不能插入
mysql> insert into meiju values(8);
ERROR 1265 (01000): Data truncated for column 'f1' at row 1
mysql> insert into meiju values("8");
ERROR 1265 (01000): Data truncated for column 'f1' at row 1
mysql> select * from meiju;
+------+
| f1 |
+------+
| 1 |
| 2 |
| 2 |
| 6 |
+------+
改表
mysql> alter table meiju modify f1 enum("a","b","c","d","e","f");
Query OK, 4 rows affected (0.39 sec)
Records: 4 Duplicates: 0 Warnings: 0
可以自动将记录当序号匹配成新的字段值(挺神奇)
mysql> select * from meiju;
+------+
| f1 |
+------+
| a |
| b |
| b |
| f |
+------+
一个记录只能有一个枚举值 不像set 可以累加
mysql> insert into meiju values(7);
ERROR 1265 (01000): Data truncated for column 'f1' at row 1
注意最好输入的是值得时候值要加引号 否则当作序号来处理
当带引号的数字不符合枚举要求时会试一试当作序号合适不合适
如 insert into meiju values("7");
7不在枚举值内 就插入第7个值 如果没有7个值则报错
集合 和 枚举的区别
1 集合可以有64个值 枚举有65535个
2 集合的序号是 1 2 4 8 16 枚举是 1 2 3 4 5 6
3 集合一个字段值可以有好几个值
+-------+
| f1 |
+-------+
| f,m |
+-------+
而枚举只能有一个