mysql索引-------10你还需要读它

1.

我们先看一个sql语句:

select * from it where userid =4

上面这个sql语句如果添加了userid作为索引,那么这条语句是会使用索引的.

再看下面这个: 

select * from it where userid + 1 =  5

上面这个语句是不会使用userid索引的,不为什么,因为索引列不能参与计算,你可以写成where userid = 5-1,但不能写成where userid +1 =5

2.

对于it表,涉及的可能不是一个sql语句,这些sql语句可能有各种各样的查法,那么每个sql语句我都设计一个索引怎么样?

事实上,这对于查询来说是极好的。但是对于维护索引是极差的。你最好使用较少的索引高效的执行本表的sql语句。

比如:

针对it表,可能会有以下三个查询:

select * from it where userid = 1 ;

select * from it where style = 4 ;

select * from it where userid = 1 and style =4;

此时可以创建(userid)(style)  (userid,style)这两条索引。

但明显是浪费了。(userid,style)比(userid)性能弱不了多少,且符合从左至右。

所以可以建立(style)(userid,style)两条索引。

但还可以更进一步,只创建(style,userid)这一条索引,但需要修改下sql语句:

select * from it where userid = 1 and style in (0,1,2,3,4);

select * from it where style = 4 ;

select * from it where userid = 1 and style =4;

style的值比较少,就这几个,而且In语句是可以使用索引的。

这样只需要一条索引就可以适用三条语句。

3.

select * from it where userid =4

如果使用了userid作为索引,它的效率依然不是最好的。

你可以尝试这条sql语句和覆盖索引结合在一起。

select * from it inner join (select id from it where userid=4) AS itid on it.id = itid.id

这里面使用了双语句双索引,select id from it where userid=4使用了覆盖索引取得了id(userid索引怎么取到的id?InnoDb存储的就是主键啊),然后id是主键索引来查表。 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值