Mysql枚举不搜索没有引号值的记录

时间:2018-02-14 11:25:25

标签: mysql sql

我的表字段包含enum enum('0','1','2','3','4','5','6')。

在我尝试使用IN(1)时查询它不起作用但是当我使用IN(“1”)时它正在工作。

如果我使用In(1,2)它正在工作。

所以当“IN”子句中有一个值时,它应该没有引用

4 个答案:

答案 0 :(得分:2)

ENUM值已定义并存储为字符串。可以通过字符串值或数字索引值(从1而不是0开始)访问它们。

你的枚举值从'0'开始,其数字索引值为1.因此,可以使用IN(1,2)从查询中获取一些数据,但这些数字将被视为索引,你实际上会得到返回的数据,其中枚举值为'2'和'3'(可能不是你认为你会得到的)。

pd.read_csv()不起作用,因为您没有索引值为1的数据(emum值='0') IN(1)确实有效,因为您确实拥有枚举值为“1”的数据

试试这个实例 http://sqlfiddle.com/#!9/3993b/1

或阅读the mysql documentation

中关于处理枚举文字的部分

答案 1 :(得分:1)

您可以将值用作字符串或整数,IN()函数支持这两种类型。

  

IN运算符允许您在WHERE子句中指定多个值。

通常IN()函数用于倍数值,但它也支持单值。对我来说,所有查询都在运作

SELECT * FROM `your_table` WHERE `id` IN('4') // String Number
SELECT * FROM `your_table` WHERE `id` IN('4','2','1') // String Multiple Number
SELECT * FROM `your_table` WHERE `id` IN(1) // Single Integer
SELECT * FROM `your_table` WHERE `id` IN(1,2,4) // Multiple Integer

答案 2 :(得分:1)

Avoid using number as 'enumeration values'

Doucumenation quotes-We strongly recommend that you do not use numbers as enumeration values, because it does not save on storage over the appropriate TINYINT or SMALLINT type, and it is easy to mix up the strings and the underlying number values (which might not be the same) if you quote the ENUM values incorrectly. If you do use a number as an enumeration value, always enclose it in quotation marks. If the quotation marks are omitted, the number is regarded as an index. See Handling of Enumeration Literals to see how even a quoted number could be mistakenly used as a numeric index value.'

Link- https://dev.mysql.com/doc/refman/5.7/en/enum.html#enum-limits

答案 3 :(得分:0)

enum支持通过数字索引值或直接引用来访问值。

根据MySQL documentation on ENUM

  

...强烈建议您不要使用数字作为枚举值,
  因为它不能通过适当的TINYINT或SMALLINT类型节省存储,
  并且很容易混合字符串和基础数字值
   (如果您错误地引用ENUM值,则可能不相同)。

     

如果您使用数字作为枚举值,请始终将其用引号括起来   如果省略引号,则将该数字视为索引。

示例

mysql> drop table if exists so_q48786040;
mysql> CREATE TABLE so_q48786040(e ENUM('6', '5', '4', '3', '2', '1', '0'));
mysql> INSERT INTO so_q48786040 VALUES( 2 ), ( 4 ), ( 7 ), ( '6' );
Query OK, 4 rows affected (0.05 sec)
Records: 4  Duplicates: 0  Warnings: 0

选择所有行,返回值5,3,0,6

mysql> SELECT * FROM so_q48786040;
+------+
| e    |
+------+
| 5    |
| 3    |
| 0    |
| 6    |
+------+
4 rows in set (0.00 sec)

选择特定指数。结果将按照定义的枚举索引的顺序排列。

mysql> SELECT * FROM so_q48786040 WHERE e IN( 7, 4 );
+------+
| e    |
+------+
| 3    | -- <--- at index 4
| 0    | -- <--- at index 7
+------+
2 rows in set (0.00 sec)

选择特定的引用文字。结果将按照定义的枚举索引的顺序排列。

mysql> SELECT * FROM so_q48786040 WHERE e IN( '6', '3', '0' );
+------+
| e    |
+------+
| 3    |
| 0    |
| 6    |
+------+
3 rows in set (0.00 sec)

选择不存在的条目。返回空集,因为未插入“4”

mysql> SELECT * FROM so_q48786040 WHERE e IN( '4' );
Empty set (0.00 sec)

注意

  • 建议在索引0处定义文字。
  • NULL值的索引为NULL