拯救mysql單錶資料

2021-07-06 02:13:20 字數 1963 閱讀 5140

一早來上班時,突然被告知mysql生產庫上某張重要表上,100多萬條資料只剩下幾百條了。

嚇得我,趕緊連上生產庫檢視。果真如此。剩下的資料都是今天早上9點以後產生的,說明9點前對該錶做了delete操作。

事已至此,接下來重要的是兩件事,一恢復資料,二找出原因以驗證恢復方法是否妥當。

恢復資料資料的第一步是找乙個空的庫,把今天凌晨0點的備份還原上去(整庫恢復)。

新建schema,要和生產庫的schema名一致。(後面做時間點恢復時需要。)

create schema 'yourschemaname' default character set utf8 collate utf8_bin

接著恢復庫

mysql --host=localhost --user=root -p***x --port=3306 --default-character-set=utf8 --database=yourschemaname <"backup.sql"&

恢復好以後,把問題表的資料匯出來。-t引數可以不把錶結構匯出來。

mysqldump -uroot -p***x  tablename -t> /home/backup/table.sql 

再把匯出來的sql問直接放到生產庫執行。

mysql -uroot -p***x

mysql>source \table.sql 

ok,到目前為止資料已經恢復到今天早上0點,0點到早上9點間的資料要用binlog進行修復。

首先要找到,刪除資料問題的sql語句。需要從當天的binlog裡查詢

我試了下面的語句,都沒找到原因。

mysqlbinlog -d   'yourschemaname'  mysql-bin.000213|grep -i "delete from table_name"

mysqlbinlog -d   'yourschemaname'  mysql-bin.000213|grep -i truncate

後來有人提醒是不是有人drop 後重建了表,發現果然如此。

mysqlbinlog -d   'yourschemaname'  mysql-bin.000213|grep -i drop

#151022  9:38:02 server id 1  end_log_pos 898252086 crc32 0xaa72e4af  query thread_id=444079 exec_time=4 error_code=0

set timestamp=1445477882/*!*/;

set @@session.foreign_key_checks=0, @@session.unique_checks=0/*!*/;

set @@session.sql_mode=524288/*!*/;

drop table if exists `***xx` /* generated by server */

取得當天的binlog,執行紅字之前的語句即可。

mysqlbinlog  --stop-position=898252085 mysql-bin.000213>diff.sql

mysql>source \diff.sql

這樣,我們的新庫上的資料已經恢復到了drop之前的狀態。由於生產庫還在產生資料。所以只能把新庫的對應表的差分資料反映過去。

create table temp1 as select * from ***x where create_date > date('2015-10-22 00:00:00');

temp1的資料是今天新插入的資料,可以直接匯入生產庫。

但是今天跟新的資料,需要逐條重新執行。

create table temp2 as select * from ***x where update_date > date('2015-10-22 00:00:00') and create_date <> update_date ;

把今天更新的資料找出來,剩下的就交給業務人員去修復資料了



MySQL單錶資料查詢

在mysql資料查詢中,最基本的查詢語句是 select from table name where condition 假設資料庫中表students中有id,name,age,birthday四個字段 代表表中所有字段,在查詢時可結合實際選取自己需要查詢的字段,即 select name,id,...

MySQL查詢資料之單錶查詢

單錶查詢的語法 select 字段 from 表名 查詢表中的所有資料 where 條件 加where查詢表的部分資料 eg select stu name,gender,stu on from student 不同欄位用逗號隔開 可以替換所有的字段細資訊 eg select from 表名 字段重...

MySQL單錶或多表清空資料

現在要清空資料庫多張表資料,一般來說我們都會直接寫delete truncate table 但在實際開發中我們可能要一下清空很多張表,很顯然我們再通過手敲 一張一張刪就不太實際了,有的小夥伴說了,我可以通過圖形化介面一張一張清空啊,可以是闊以,但效率就顯而易見了。將上面sql語句的結果以excel...