解决mysql主从1062主键冲突报错脚本

**整体思路:首先判断是否是1062报错,如果是再从报错信息中获取库名,表名,字段及字段值,然后在从库中删除相应的数据,重启从库sql线程。**
#!/bin/bash
user=root
passwd=123456

    mysql -h 127.0.0.1 -u $user -p$passwd -e "show slave status\G" | grep HA_ERR_FOUND_DUPP_KEY
    if [ $? -eq 0 ]
    then
        sql_thread=`mysql -h 127.0.0.1 -u $user -p$passwd -e "show slave status\G" | egrep 'Slave_SQL_Running' | awk '{print $2}' | head -n 1`
        error_id=`mysql -h 127.0.0.1 -u $user -p$passwd -e "show slave status\G" | egrep Last_Errno | awk '{print $2}'`

        if [ "$sql_thread" == No ] && [ "$error_id" == 1062 ]
        then
            dupl_value=`mysql -h 127.0.0.1 -u $user -p$passwd -e "show slave status\G" | grep Last_Error | awk '/Duplicate entry/' | awk -F "'" '{print $2}'`
            db_name=`mysql -h 127.0.0.1 -u $user -p$passwd -e "show slave status\G" | grep Last_Error | awk '{print $9}' | awk -F "." '{print $1}'`
            table_name=`mysql -h 127.0.0.1 -u $user -p$passwd -e "show slave status\G" | grep Last_Error | awk '{print $9}' | awk -F "." '{print $2}' | awk -F";" '{print $1}'`
            column=`mysql -h 127.0.0.1 -u $user -p$passwd -Nse "desc $db_name.$table_name" | grep PRI | awk '{print $1}'`

            mysql -h 127.0.0.1 -u $user -p$passwd -e "delete from $db_name.$table_name where $column = $dupl_value;"
            mysql -h 127.0.0.1 -u $user -p$passwd -e "start slave sql_thread;"
            sleep 0.05
        fi
    fi

你可能感兴趣的:(shell,mysql)