mysql查询索引总结

来源:互联网 发布:b2b2c php开源 编辑:程序博客网 时间:2024/05/16 15:30

mysql查询索引总结

1.使用以下语句查看表索引:

show index from tablename;

2.使用以下语句查看执行计划:

explain select * from tablename;

注意查看可用的索引和实际使用的索引。

3.查看慢查询

show variables like '%slow%';

4.联合索引使用的时候,优先从最左边的开始用。
例如创建的联合索引为(starttime,endtime,cardnum),则以下查询可以用到联合索引:

1)select * from table where starttime >='2016-10-30 10:34:34';2)select * from table where starttime >='2016-10-30 10:34:34' and endtime <='2016-10-31 10:34:34';3)select * from table where starttime >='2016-10-30 10:34:34' and cardnum = '8897654';

以下查询无法使用联合索引:

1)select * from table where endtime >='2016-10-30 10:34:34';2)select * from table where endtime >='2016-10-30 10:34:34' and starttime <='2016-10-31 10:34:34';

结论:在创建多列索引时,要根据业务需求,where子句中使用最频繁的一列放在最左边。

5.exists使用总结:
exists对外表用loop逐条查询,每次查询都会查看exists的条件语句,当 exists里的条件语句能够返回记录行时(无论记录行是的多少,只要能返回),条件就为真,返回当前loop到的这条记录,反之如果exists里的条 件语句不能返回记录行,则当前loop到的这条记录被丢弃,exists的条件就像一个bool条件,当能返回结果集则为true,不能返回结果集则为 false