mysql - 慢查询日志、explain详解

本文详细介绍了如何开启MySQL慢查询日志,以及使用explain命令解析SQL执行计划的方法。涵盖了慢查询配置、常见执行类型及其优化建议,帮助读者深入理解SQL执行效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 开启慢查询日志

show variables like 'slow_query_log';
show variables like 'slow_query%';

show variables like 'long_query_time';

set global slow_query_log = 'ON';
set global slow_query_log_file = 'C:/Users/Desktop';
set global long_query_time = 1;


二  explain命令详解(待续。。。)

explain 用于查看执行计划的信息。 

explain select username from a, b where a.id = b.id;
explain select username from a, b using(id);


table: 表名
type: 连接的类型(效率递减)
    system:从const中查询的记录,有且仅有一行满足条件。或者说查询的表中只有一条记录。
    const:由主键或者唯一键作为查询条件,由于只有一条,查询的记录被优化器视为常量
    eq-ref:唯一性索引扫描。
        eg. (B.MID 为 主键, A.MID 可能为普通字段) select * from A, B where A.MID = B.MID;
    ref:非唯一性索引扫描。索引不是主键或者唯一索引。
        eg. (A表中可能含有多个相同的sId。sId不具有唯一性。) select * from A where A.sId = 10;
    fulltext:全文索引,(优先级高于普通索引)
        eg. alter table A add fulltext(username);
            select * from A match(username) against('tom', 'selina');
    ref_or_null:在ref的基础上增加对null的检测
        eg. select * from A where A.sId = 10 or sId is null;
        
        coalesce() ifnull() isnull() nullif()

    index_merge:索引合并
        eg. (username,password都是索引) select * from user where username = 'tom' and password = 'tom1';

    unique_subquery
        eg. (id是主键) select * from A where id in (select id from A where userId = 10);

    index_subquery
        eg. (username普通索引) select * from A where username in (select username from A where company = "Oracle");

    range: 检索给定范围的索引
        eg. select * from A where A.age > 20;

    index: 先读索引,再读实际的行,结果还是全表扫描
        eg. select count(*) from A;

    all: 全表扫描
        eg. select * from A;
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值