mysql 禁止使用enum_MySQL慎用 ENUM 字段
前言:在網(wǎng)上看了很多文章,大家都是推薦 MySQL 要慎用 ENUM 字段,但是原理感覺還是有點模糊。今天我們就從官網(wǎng)來818這些東西
1、關于 ENUM?遷移的問題?
這里引用別人的一段話:但ENUM帶來的問題也不少,比如數(shù)據(jù)遷移的時候,他幾乎不可能被其他數(shù)據(jù)庫所支持,如果 ENUM 里面是字符串,對于其他數(shù)據(jù)庫來說就更郁悶了,還不能設為tinyint等類型的字段
2、關于 ENUM 索引的問題?
純數(shù)字類型的不建議用枚舉類型,這是因為在 ENUM 內(nèi)部維護有一個隱形的索引,也是按數(shù)字排列的,容易混淆;添加枚舉值也是一個問題,如果添加在最后還好,如果添加在中間什么位置的話,原來的隱藏索引將不再起作用
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.
ValueIndex
NULLNULL
''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 值的,這個就比較尷尬了,而且沒有辦法優(yōu)化
4、插入的值問題
如果插入的值比ENUM設定的值大,會默認保存成接近的那個值;插入的值不能包含函數(shù),不能傳遞參數(shù)
numbers ENUM('0','1','2')
mysql> INSERT INTO t (numbers) VALUES(2),('2'),('3');
mysql> SELECT * FROM t;
+---------+
| numbers |
+---------+
| 1 |
| 2 |
| 2 |
+---------+
所以如果插入的值是數(shù)字型的,建議用tinyint,如果插入的值是字符型的,建議用char。如果真想用 ENUM 也是可以得,前提是要了解到 ENUM 的弊端,就可以有效規(guī)避這些問題
參考文檔:https://dev.mysql.com/doc/refman/5.7/en/enum.html#enum-limits
為了方便大家交流,本人開通了微信公眾號,和QQ群291519319。喜歡技術的一起來交流吧
總結
以上是生活随笔為你收集整理的mysql 禁止使用enum_MySQL慎用 ENUM 字段的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python在另一个函数中使用其他函数的
- 下一篇: python如何查看有什么模块_在pyt