Java系统里写的sql,都必须符合最左前缀匹配原则,确保你所有的sql都可以使用上这个联合索引,通过索引来查询
create index(shop_id, product_id, gmt_create)
全列匹配
sql里,where条件里用了这3个字段,那么就一定够可以用到联合索引。
select * from product where shop_id=1 and product_id=1 and gmt_create = ‘2019-01-01 10:00:00’
最左前缀匹配
你的sql里,正好用到了联合索引最左边的一个或者几个列,那么也可以用上这个索引,在索引里查找的时候就用最左边的几个列。
select * from product where shop_id=1 and product_id = 1 这个是没问题的,可以用上这个索引。
最左前缀匹配,中间没有匹配
在你的sql里,用了联合索引的第一个列和第三个列,那么会按照第一个列值在索引里找,找完以后对结果集扫描一遍根据第三个列来过滤,第三个列是不走索引去搜索的,就是有一个额外的过滤工作,但是还能用到索引,所以也还好。
select * from product where shop_id = 1 and gmt_create=’2019-01-01 10:00:00’
先根据shop_id在索引里找,找到比如100条记录,然后对这100条记录再次扫描一遍,过滤出来gmt_create=’2019-01-01 10:00:00’的行
没有最左前缀匹配
一定不会用索引,这个错误千万别犯
select * from product where product_id=1
前缀匹配
like操作,必须要是like ‘2019%’这种才可以用上索引
select * from product where shop_id=1 and product id = 1 and gmt_create like ‘2019%’
范围列匹配
符合最左前缀的规则才可以范围,范围之后的列就不用索引了
select * from product where shop_id>=1 and product_id=1
这里就在联合索引中根据shop_id来查询了
使用函数
如果你对某个列用上了函数,那么那一列不用索引
select * from product where shop_id=1 and substring(product_id)=2
上面根据shop_id在联合索引中查询