前言
这两天在家看《数据库概论》,讲到索引,除了我经常见到的B+树索引,HASH索引,还有顺序文件上的索引,位图索引。
应用场景
有张表名为table的表,由三列组成,分别是姓名、性别和婚姻状况,其中性别只有男和女两项,婚姻状况由已婚、未婚、离婚这三项,该表共有100w个记录。现在有这样的查询: select * from table where Gender=‘男’ and Marital=“未婚”;
1)不使用索引:一行一行遍历,效率降低
2)B+树索引:此索引适合重复元素较少的字段,性别只有两种值,对于B+树索引并不适合,在查询的时候数据库往往会放弃索引。
位图索引出场
对于性别,形成两个字符串,男是10100...,女是01011...
对于婚姻状况,形成三个向量
当我们使用查询语句“select * from table where Gender=‘男’ and Marital=“未婚”;”的时候 首先取出男向量10100...,然后取出未婚向量
00100...,将两个向量做and操作,这时生成新向量00100...,可以发现第三位为1,表示该表的第三行数据就是我们需要查询的结果。
位图索引使用条件
位图索引适合只有几个固定值的列,但是适合静态数据,不适合频繁更新的数据。
原因:索引需要维护,频繁更新的时候,同时也要加行锁,这个时候会加行锁。