下面的SQL索引失效【使用*或多了字段】:mysql
小表驱动大表:小的数据集驱动大的数据集sql
1.当B表的数据集必须小于A表的数据集时,用in优于exists select * from A where id in (select id from B) 等价 for select id from B for select *from A where A.id=B.id 2.当A表的数据集小于B表的数据集时,用exists优于in select *from A where exists (select 1 from B where B.id=A.id); 等价 for select *from A for select *from B where B.id=A.id
创建索引:key abc(a,b,c) order by使用索引最左前缀原则:(有序索引排序,using index) --order by a --order by a,b --order by a,b,c --order by a desc,b desc,c desc(升降序一致) 若是where使用索引的最左前缀定义为常量,则使用索引且是有序索引排序(using index): --where a=const order by b,c --where a=const and b=const order by c --where a=const and b>const order by b,c 产生文件排序(using filesort): --order by b(非最左前缀) --order by b,a(顺序颠倒) --order by a asc,b desc,c desc (排序不一致) --where d=const order by b,c (a丢失) --where a=const order by c(b丢失) --where a=const order by a,d(d不是索引的一部分) --where a in(..) order by b,c(范围查询)
在my.cnf文件中[mysqld]增长或修改参数: slow_query_log=1 slow_query_log_file=/文件存储路径/fileName.log【若没有指定,系统默认给一个指定的文件host_name-slow.log】查看达到写入慢查询日志的阀值:SHOW VARIABLES LIKE 'long_query_time%';【默认状况下为10秒,即查询时间大于10秒的sql会记录到日志中】设置阀值:set global long_query_time=数值;【设置结束后须要新开一个会话或从新链接才看见修改信息,或使用show global variables like 'long_query_time'查看】查看当前系统的慢查询SQL总条数:show global status like '%Slow_queries%';