DBA MySQL枚举集合
ENUM
枚举类型从众多选项成员中提取出一个选项,类似于单选的概念,最大可指定65535个选项。
如果插入值不在其选项成员中,将会插入空字符。
CREATE TABLE userinfo(
id INT PRIMARY KEY AUTO_INCREMENT COMMENT "用户编号",
name CHAR(12) NOT NULL COMMENT "用户姓名",
age TINYINT(3) NOT NULL DEFAULT 0 COMMENT "用户年龄",
gender ENUM("male", "female", "unknow") DEFAULT "unknow" COMMENT "用户性别"
) ENGINE innodb CHARSET utf8mb4 COLLATE utf8mb4_general_ci;
尝试对其进行插入操作,如果插入选项不在ENUM
的选项成员中,则结果为空:
M > INSERT INTO
userinfo (name, age, gender)
VALUES
("Jack", 22, "other");
M > SELECT * FROM userinfo LIMIT 1;
+----+--------------+-----+--------+
| id | name | age | gender |
+----+--------------+-----+--------+
| 1 | Jack | 22 | |
+----+--------------+-----+--------+
SET
集合类型从众多选项成员中提取出多个选项,类似于多选的概念,最大可指定64个选项。
如果插入值中有一个不在其选项成员中,将会插入空字符,在其选项成员中的值将会被正确插入。
CREATE TABLE userinfo(
id INT PRIMARY KEY AUTO_INCREMENT COMMENT "用户编号",
name CHAR(12) NOT NULL COMMENT "用户姓名",
age TINYINT(3) NOT NULL DEFAULT 0 COMMENT "用户年龄",
gender ENUM("male", "female", "unknow") DEFAULT "unknow" COMMENT "用户性别",
hobby SET("basketball", "football", "volleyball", "unknow") DEFAULT "unknow" COMMENT "用户爱好"
) ENGINE innodb CHARSET utf8mb4 COLLATE utf8mb4_general_ci;
对集合类型字段进行插入时,可按照选项1,选项2
的方式进行插入。如下所示:
M > INSERT INTO
userinfo(name, age, gender, hobby)
VALUES
("Jack", 22, "male", "basketball,football");
M > SELECT * FROM userinfo LIMIT 1;
+----+--------------+-----+--------+---------------------+
| id | name | age | gender | hobby |
+----+--------------+-----+--------+---------------------+
| 1 | Jack | 22 | male | basketball,football |
+----+--------------+-----+--------+---------------------+
使用建议
无论是ENUM
还是SET
,选项成员都应该是字符类型。