使用按位函数对BIT字段进行查询时,MySQL不使用索引 [英] MySQL doesn't use indexes when query over BIT field using bitwise functions

查看:434
本文介绍了使用按位函数对BIT字段进行查询时,MySQL不使用索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MySQL表中有一个BIT类型的字段.我想使用位值存储记录的状态,例如:

I have a field of type BIT in my MySQL table. I want to store statuses of the record using bit value, for example:

1 = status1
2 = status2
4 = status3
8 = status4

每个记录可以一次具有多种状态.对于status1和status3,该值将为1 + 4 =5.我可以使用以下方法查询表中所有具有status3的记录:

Each record can have many statuses at once. For status1 and status3 the value will be 1 + 4 = 5. I can query table for all records with status3 using:

SELECT * 
  FROM `table` 
 WHERE `statuses` & 4 

我在statuses上有索引,但是EXPLAIN告诉我没有使用索引.在这种情况下可以使用索引吗?

I have index on statuses, but EXPLAIN tells that no index is used. Can I use index in such situation?

P.S.使用单独的多对多链接表是更规范的解决方案,但是我希望对此具有更多的扁平"结构.

P.S. Using separate many-to-many linking table is more normalized solution, but I'd like to have more 'flat' structure for this.

推荐答案

优化器将很难在位域上使用索引.考虑设置了位2(值"4")的所有不同值:4、5、6、7、12、13、14、15、15、20、21、22、23,...优化器将如何提高效率使用它吗?

It would be difficult for the optimizer to make use of an index on a bitfield. Consider all the different values which have bit 2 (value "4") set: 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, ... How would the optimizer make efficient use of that?

这篇关于使用按位函数对BIT字段进行查询时,MySQL不使用索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆