MYSQL排查使用CPU多的SQL

背景

数据库: mysql 5.7.38

业务模拟: sysbench

问题sql: select count(*) from db1.sbtest1,db1.sbtest2;

根据监控发现数据库所在服务器CPU使用率很高. 故想找找是哪些SQL在使用CPU.

排查过程

使用top找到使用CPU多的MYSQL进程

本次为模拟环境. sysbenc模拟业务.

<code style="margin-left:0">top</code>

找到使用CPU多的线程

<code style="margin-left:0">top -H -p 3895  #PID是mysqld的进程ID</code>

找到线程号为 6361 的SQL

<code style="margin-left:0">select * from performance_schema.threads where THREAD_OS_ID=6361\G</code>

解决办法

发现执行时间长的SQL是两张表关联查询,没得条件(正常业务应该不会有这种SQL..). 所以加个条件就行

<code style="margin-left:0">select count(*) from db1.sbtest1 as aa, db1.sbtest2 as bb where aa.id=36203; -- 这是测试SQL, 实际业务请以实际SQL为准</code>

也可以使用profile来看SQL使用的CPU时间在哪

<code style="margin-left:0">(root@127.0.0.1) [(none)]> set profiling = 1;
Query OK, 0 rows affected, 1 warning (0.00 sec)

(root@127.0.0.1) [(none)]> select count(*) from db1.sbtest1 as aa, db1.sbtest2 as bb where aa.id=36203;
+----------+
| count(*) |
+----------+
|   133686 |
+----------+
1 row in set (0.02 sec)

(root@127.0.0.1) [(none)]> show profile cpu;
+----------------------+----------+----------+------------+
| Status               | Duration | CPU_user | CPU_system |
+----------------------+----------+----------+------------+
| starting             | 0.000096 | 0.000072 |   0.000020 |
| checking permissions | 0.000031 | 0.000024 |   0.000006 |
| checking permissions | 0.000031 | 0.000024 |   0.000007 |
| Opening tables       | 0.000073 | 0.000057 |   0.000015 |
| init                 | 0.000044 | 0.000035 |   0.000010 |
| System lock          | 0.000092 | 0.000072 |   0.000020 |
| optimizing           | 0.000127 | 0.000128 |   0.000000 |
| statistics           | 0.000112 | 0.000112 |   0.000000 |
| preparing            | 0.000036 | 0.000036 |   0.000000 |
| executing            | 0.000028 | 0.000027 |   0.000000 |
| Sending data         | 0.020081 | 0.020077 |   0.000000 |
| end                  | 0.000020 | 0.000016 |   0.000000 |
| query end            | 0.000016 | 0.000016 |   0.000000 |
| closing tables       | 0.000016 | 0.000016 |   0.000000 |
| freeing items        | 0.000079 | 0.000079 |   0.000000 |
| cleaning up          | 0.000025 | 0.000025 |   0.000000 |
+----------------------+----------+----------+------------+
16 rows in set, 1 warning (0.00 sec)

(root@127.0.0.1) [(none)]> 
</code>

未经允许不得转载:木盒主机 » MYSQL排查使用CPU多的SQL

赞 (0)

相关推荐

    暂无内容!