前言:在网上看了很多文章,大家都是推荐 MySQL 要慎用 ENUM 字段,但是原理感觉还是有点模糊。今天我们就从官网来818这些东西
1、关于 ENUM 迁移的问题?
这里引用别人的一段话:但ENUM带来的问题也不少,比如数据迁移的时候,他几乎不可能被其他数据库所支持,如果 ENUM 里面是字符串,对于其他数据库来说就更郁闷了,还不能设为tinyint等类型的字段
2、关于 ENUM 索引的问题?
纯数字类型的不建议用枚举类型,这是因为在 ENUM 内部维护有一个隐形的索引,也是按数字排列的,容易混淆;添加枚举值也是一个问题,如果添加在最后还好,如果添加在中间什么位置的话,原来的隐藏索引将不再起作用
Index Values for Enumeration Literals
Each enumeration value has an index:
The elements listed in the column specification are assigned index numbers, beginning with 1.
The index value of the empty string error value is 0. This means that you can use the following SELECT statement to find rows into which invalid ENUM values were assigned:
mysql> SELECT * FROM tbl_name WHERE enum_col=0;
The index of the NULL value is NULL.
The term “index” here refers to a position within the list of enumeration values. It has nothing to do with table indexes.
For example, a column specified as ENUM('Mercury', 'Venus', 'Earth') can have any of the values shown here. The index of each value is also shown.
Value Index
NULL NULL
'' 0
'Mercury' 1
'Venus' 2
'Earth' 3
An ENUM column can have a maximum of 65,535 distinct elements. (The practical limit is less than 3000.) A table can have no more than 255 unique element list definitions among its ENUM and SET columns considered as a group. For more information on these limits, see Section C.10.5, “Limits Imposed by .frm File Structure”.
If you retrieve an ENUM value in a numeric context, the column value's index is returned. For example, you can retrieve numeric values from an ENUM column like this:
mysql> SELECT enum_col+0 FROM tbl_name;
Functions such as SUM() or AVG() that expect a numeric argument cast the argument to a number if necessary. For ENUM values, the index number is used in the calculation.
3、ENUM 字段 NULL 值问题
ENUM 字段默认是可以插入 NULL 值的,这个就比较尴尬了,而且没有办法优化
4、插入的值问题
如果插入的值比ENUM设定的值大,会默认保存成接近的那个值;插入的值不能包含函数,不能传递参数
numbers ENUM('0','1','2')
mysql> INSERT INTO t (numbers) VALUES(2),('2'),('3');
mysql> SELECT * FROM t;
+---------+
| numbers |
+---------+
| 1 |
| 2 |
| 2 |
+---------+
所以如果插入的值是数字型的,建议用tinyint,如果插入的值是字符型的,建议用char。如果真想用 ENUM 也是可以得,前提是要了解到 ENUM 的弊端,就可以有效规避这些问题
参考文档:https://dev.mysql.com/doc/refman/5.7/en/enum.html#enum-limits
为了方便大家交流,本人开通了微信公众号,和QQ群291519319。喜欢技术的一起来交流吧