由于ENUM
字段实际上只是一个INT UNSIGNED
,因此如果您对 s 使用整数值,它将无法按预期工作ENUM
。例如, your ENUM
of '0'
, 在内部存储为 numeric 1
,而 your '1'
, 存储为 numeric 2
。令人惊讶的是,空字符串''
在内部存储为0
. 这是一个无法按预期工作的示例:
mysql> CREATE TABLE enumtest (
-> id int unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> a ENUM ('0','1','2','3') NOT NULL DEFAULT '0',
-> i int unsigned NOT NULL DEFAULT 0
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO enumtest SET a = 0, i=0;
Query OK, 1 row affected, 1 warning (0.01 sec)
mysql> SHOW WARNINGS;
+---------+------+----------------------------------------+
| Level | Code | Message |
+---------+------+----------------------------------------+
| Warning | 1265 | Data truncated for column 'a' at row 1 |
+---------+------+----------------------------------------+
1 row in set (0.00 sec)
mysql> INSERT INTO enumtest SET a = '0', i=0;
Query OK, 1 row affected (0.01 sec)
mysql> INSERT INTO enumtest SET a = 1, i=1;
Query OK, 1 row affected (0.01 sec)
mysql> INSERT INTO enumtest SET a = '1', i=1;
Query OK, 1 row affected (0.00 sec)
mysql> SELECT a,0+a,i FROM enumtest;
+---+-----+---+
| a | 0+a | i |
+---+-----+---+
| | 0 | 0 |
| 0 | 1 | 0 |
| 0 | 1 | 1 |
| 1 | 2 | 1 |
+---+-----+---+
4 rows in set (0.00 sec)
mysql> SELECT SUM(a),SUM(0+a), SUM(i) FROM enumtest;
+--------+----------+--------+
| SUM(a) | SUM(0+a) | SUM(i) |
+--------+----------+--------+
| 4 | 4 | 2 |
+--------+----------+--------+
1 row in set (0.00 sec)
该子句将其0+a
强制ENUM
转换为其基础UNSIGNED
值。这相当于CAST(a AS UNSIGNED)
。