Mysql 服务性能优化配置:http://5434718.blog.51cto.com/5424718/1207526【该文章很好】
Sql查询性能优化
对Sql进行优化,肯定是该Sql运行未能达到预期;Mysql运行是基于开销的,CPU和IO。
所以第一步,监控该Sql的运行开销,找出性能瓶颈;第二步,查看该Sql的执行计划,根据执行计划 找出关键点,有针对性的进行优化。
监控Sql开销,使用profiling.
开启profiling:set profiling=1;[关闭:set profiling=0;]
查询profiling开启状态:show variables like '%profiling%';
监控Sql查询:show profiles;
一旦开启profile,最新的监控Sql会位于最下面,
查询某条Sql的详细开销信息:show profile cpu,block io for query {queryId}
根据上述信息,可以确定sql的开销类型。
2,分析sql 执行计划
使用explain {sql语句}
如:
根据各项所代表的信息,找到关键点,进行相关优化。
也可使用系统库去侦查相关信息:
如:列出查询最慢的几条Sql,
SELECT
*
FROM
performance_schema.events_statements_summary_by_digest
ORDER
BY
SUM_TIMER_WAIT
DESC
LIMIT 5;
SUM_ERRORS > 0 OR SUM_WARNINGS >
0;查询SQL执行中出现临时表的情况: SUM_CREATED_TMP_TABLES = SUM_CREATED_TMP_DISK_TABLES;
最新执行的Sql:FIRST_SEEN > (NOW() - INTERVAL 2 DAY)。
查询SQL线程及其对应的执行情况,可用:
SELECT * FROM performance_schema.threads ,该可关联 information_schema.processlist用于协助调查。
显示某一SQL的执行详情:
SELECT event_name, timer_wait/1000000000 wait_ms
FROM events_stages_history_long AS stages
JOIN (SELECT event_id
FROM events_statements_history_long
ORDER BY event_id DESC limit 1) AS statements
ON stages.nesting_event_id = statements.event_id
ORDER BY stages.event_id;
查询某线程的执行历史 :
SELECT thread_id,
CONCAT( CASE WHEN event_name LIKE 'stage%' THEN
CONCAT(' ', event_name)
WHEN event_name LIKE 'wait%' AND nesting_event_id IS NOT NULL THEN
CONCAT(' ', event_name)
ELSE IF(digest_text IS NOT NULL, SUBSTR(digest_text, 1, 64), event_name)
END,
' (',ROUND(timer_wait/1000000, 2),'μ) ') event
FROM (
(SELECT thread_id, event_id, event_name,
timer_wait, timer_start, nesting_event_id, digest_text
FROM events_statements_history_long)
UNION
(SELECT thread_id, event_id, event_name,
timer_wait, timer_start, nesting_event_id, NULL
FROM events_stages_history_long)
UNION
(SELECT thread_id, event_id, event_name,
timer_wait, timer_start, nesting_event_id, NULL
FROM events_waits_history_long)
) events
ORDER BY thread_id, event_id;