实际上,在ENUM列规范中列出的元素被分配了从1开始的索引号。这里的术语“索引”指的是在枚举值列表中的位置,它们与表索引无关。通过以下示例,我们可以展示每个MySQL枚举都有一个索引值-
mysql> Insert into marks(id,name,result)values(103,'Daksh','1'); Query OK, 1 row affected (0.06 sec) mysql> Insert into marks(id,name,result)values(104,'Shayra','2'); Query OK, 1 row affected (0.07 sec) mysql> Select * from marks; +-----+---------+--------+ | id | Name | Result | +-----+---------+--------+ | 101 | Aarav | Pass | | 102 | Yashraj | Fail | | 103 | Daksh | Pass | | 104 | Shayra | Fail | +-----+---------+--------+ 4 rows in set (0.00 sec)
在上述查询中,我们使用索引号1和2分别表示枚举值pass和fail。
空字符串的索引值为0。在插入空字符串之前,SQL模式不能是TRADITIONAL、STRICT_TRANS_TABLES或STRICT_ALL_TABLES。通过以下示例,我们可以理解它 −
mysql> SET SESSION sql_mode = ''; Query OK, 0 rows affected (0.00 sec) mysql> Insert into marks(id, name, result) values(105,'Yashraj',''); Query OK, 1 row affected, 1 warning (0.06 sec)
上面的查询将在枚举值的位置插入空字符串。 MySQL 插入空字符串并出现以下警告。
mysql> Show warnings; +---------+------+---------------------------------------------+ | Level | Code | Message | +---------+------+---------------------------------------------+ | Warning | 1265 | Data truncated for column 'Result' at row 1 | +---------+------+---------------------------------------------+ 1 row in set (0.00 sec)
现在当我们检查表格时,可以看到在ENUM字段中有一个空字符串。
mysql> Select * from marks; +-----+---------+--------+ | id | Name | Result | +-----+---------+--------+ | 101 | Aarav | Pass | | 102 | Yashraj | Fail | | 103 | Daksh | Pass | | 104 | Shayra | Fail | | 105 | Yash | | +-----+---------+--------+ 5 rows in set (0.00 sec) mysql> Select result+0 As result_index from marks; +--------------+ | result_index | +--------------+ | 1 | | 2 | | 1 | | 2 | | 0 | +--------------+ 5 rows in set (0.01 sec) From the output of above query, it is clear that the index value of the empty string is 0.
我们可以在枚举值的位置插入 NULL,因为我们不为 ENUM 列指定 NOT NULL。 NULL的索引值为NULL。例如,借助以下查询,我们在表“result”的枚举列中插入NULL,并可以检查其索引值。
mysql> Create table result(Id INT PRIMARY KEY NOT NULL, Name Varchar(10), GradeENUM('POOR','GOOD')); Query OK, 0 rows affected (0.25 sec) mysql> Insert into result(id, name, grade) values(100, 'Rahul', NULL); Query OK, 1 row affected (0.06 sec)
上面的查询在枚举值的位置插入了 NULL 值,可以使用下面的帮助查询来检查 -
mysql> Select * from result; +-----+-------+-------+ | Id | Name | Grade | +-----+-------+-------+ | 100 | Rahul | NULL | +-----+-------+-------+ 1 row in set (0.00 sec)
现在,借助下一个查询,我们可以观察到NULL的索引值为NULL。
mysql> Select Grade+0 As Grade_index from result; +-------------+ | Grade_index | +-------------+ | NULL | +-------------+ 1 row in set (0.00 sec)
以上就是如何显示每个MySQL枚举都有一个索引值?的详细内容,更多请关注php中文网其它相关文章!
已抢64915个
抢已抢27360个
抢已抢14766个
抢已抢7405个
抢已抢9281个
抢已抢18423个
抢