DBAtlas · 数据库运维图谱

使用 binlog 进行时间点恢复:找到并跳过错误的事务

MySQL备份与 PITR

命令

# 1) Find the bad event's GTID and position (narrow by time range)
mysqlbinlog --base64-output=DECODE-ROWS -vv --start-datetime='2026-10-08 20:00:00' --stop-datetime='2026-10-08 20:30:00' /var/lib/mysql/binlog.000003 | grep -B12 -iE '^(DROP|TRUNCATE)' | grep -E 'GTID_NEXT|^# at|^#[0-9]{6}|^DROP|^TRUNCATE'

# 2) Restore the backup on a separate server (the dump sets GTID_PURGED)
zcat /backup/full_2026-10-08_0200.sql.gz | mysql -h restore-db -u root -p

# 3a) Replay all binlogs skipping only the bad transaction
mysqlbinlog --exclude-gtids='af6bc361-c353-11f1-8f12-f69e63ad6c0e:23' /binlogs/binlog.000003 /binlogs/binlog.000004 | mysql -h restore-db -u root -p
# 3b) Or stop right before the bad event's GTID event
mysqlbinlog --stop-position=537205 /binlogs/binlog.000003 | mysql -h restore-db -u root -p

作用

还原备份后,按顺序回放 binlog,将数据库恢复到所需时间点。启用 GTID 时,已包含在备份中的事务会被自动跳过;--exclude-gtids 只去除错误的操作,并保留其后的所有变更。

适用场景

在错误的 DROP / DELETE / UPDATE 之后,用于在不丢失备份与事故之间所做变更的情况下进行恢复。

注意

在单独的服务器上还原,而不是在生产环境;验证后只迁移受影响的表。--start/--stop-datetime 按运行 mysqlbinlog 的机器所在时区解释。--stop-position 只适用于给出的最后一个文件;对于多个文件,请用单独的命令完整回放前面的文件。--exclude-gtids 只对独立的操作是安全的;如果之后的事务写入了被删除的表,它们也会失败。所需的 binlog 不得在源上被清除;binlog 保留期至少要长于一个备份间隔。

在 DBAtlas 中打开 →

相关内容