#!/bin/sh
date_ago=`date +%Y-%m-%d\ %H:%M:%S --date='2 hours ago'` #获取2小时之前的时间点,因为我的crontab里面每2小时执行一遍该脚本
alias mysql_con='mysql -uuser -ppwd'
datebase=test
#以下两行操作会在test库里创建query_review表,同时将分析结果存储到两张表里
pt-query-digest --history u=user,p=pwd,D=$datebase /mysqldata/dev-env-slow.log --no-report
pt-query-digest --review u=user,p=pwd,D=$datebase /mysqldata/dev-env-slow.log --no-report
rm -f /tmp/slow_query_inc 2> /dev/null #清空存放上次结果的文件
#从query_review表查询出'first_seen'时间在2小时以内的'checksum',并组织成 checksum1,checksum2的形式,以便后面放在sql语句的in条件里
#where条件保证只查询第一次出现的慢查询信息,避免重复提醒
check_sum=`mysql_con -N -s -e "SELECT checksum FROM percona_schema.query_review where first_seen > '$date_ago'" 2>/dev/null|awk '{printf("%s,",$0)}'|sed 's/,$//'`
#根据上面查出的checksum值从query_history表查出慢查询相关信息
if [ ! -z $check_sum ];then
mysql_con -e "
SELECT
checksum,
sample AS Statment,
host_min AS Host,
db_min AS DB,
ts_max AS Time,
ts_cnt as Counts,
query_time_pct_95 AS Query_Time,
Rows_sent_pct_95 AS Rows_Sent,
Rows_examined_pct_95 AS Rows_Examined
FROM
$datebase.query_history
WHERE
checksum in ($check_sum)
AND
ts_max in (select max(ts_max) from $datebase.query_history where checksum in ($check_sum) group by checksum)\G
" 2> /dev/null >> /tmp/slow_query_inc
if [ -s /tmp/slow_query_inc ];then #/tmp/slow_query_inc文件有内容才发邮件
mail -s 'slow_log in last 2 hours----from Dev' k@test.com < /tmp/slow_query_inc
fi
fi