二進行日志的格式為row
mysql> show variables like 'binlog_format'; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | binlog_format | ROW | +---------------+-------+ 1 row in set (0.00 sec)
在testdb庫下執行
mysql> select * from t1; +----+------+ | id | name | +----+------+ | 1 | NULL | | 2 | chen | | 3 | li | +----+------+ 3 rows in set (0.00 sec) mysql> select * from t2; +------+--------+ | id | course | +------+--------+ | 1 | NULL | | 2 | chen | | 3 | math | +------+--------+ 3 rows in set (0.00 sec) mysql> truncate table t1; mysql> delete from t2;
執行命令:mysqlbinlog --no-defaults -vv good.000001:主要看紅色加粗字體部分:
# at 2162 #160303 11:02:51 server id 4 end_log_pos 2248 CRC32 0x3544cc1f Query thread_id=2755623 exec_time=0 error_code=0 SET TIMESTAMP=1456974171/*!*/; truncate table t1 /*!*/; # at 2248 #160303 11:05:40 server id 4 end_log_pos 2322 CRC32 0xf5126972 Query thread_id=2756326 exec_time=0 error_code=0 SET TIMESTAMP=1456974340/*!*/; BEGIN /*!*/; # at 2322 #160303 11:05:40 server id 4 end_log_pos 2372 CRC32 0xba9c0edd Table_map: `testdb`.`t2` mapped to number 12204 # at 2372 #160303 11:05:40 server id 4 end_log_pos 2432 CRC32 0xd1433d85 Delete_rows: table id 12204 flags: STMT_END_F BINLOG ' BKrXVhMEAAAAMgAAAEQJAAAAAKwvAAAAAAEABnRlc3RkYgACdDIAAgMPAhQAA90OnLo= BKrXViAEAAAAPAAAAIAJAAAAAKwvAAAAAAEAAgAC//4BAAAA/AIAAAAEY2hlbvwDAAAABG1hdGiF PUPR '/*!*/; ### DELETE FROM `testdb`.`t2` ### WHERE ### @1=1 /* INT meta=0 nullable=1 is_null=0 */ ### @2=NULL /* INT meta=20 nullable=1 is_null=1 */ ### DELETE FROM `testdb`.`t2` ### WHERE ### @1=2 /* INT meta=0 nullable=1 is_null=0 */ ### @2='chen' /* VARSTRING(20) meta=20 nullable=1 is_null=0 */ ### DELETE FROM `testdb`.`t2` ### WHERE ### @1=3 /* INT meta=0 nullable=1 is_null=0 */ ### @2='math' /* VARSTRING(20) meta=20 nullable=1 is_null=0 */ # at 2432 #160303 11:05:40 server id 4 end_log_pos 2463 CRC32 0x225aa989 Xid = 8390829 COMMIT/*!*/; DELIMITER ; # End of log file ROLLBACK /* added by mysqlbinlog */; /*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/; /*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;
可以看到二者的不同,truncate直接是以一條語句復雜過來,而delete命令是直接把每條刪除的語句一條條記錄下來,所以假如要刪除全表的數據,用truncate命令會比用delete命令少記錄很多內容,日志內容會大減少,肯效率會更高
另外:delete與truncate還有以下的不同:
1. truncate和 delete只刪除數據不刪除表的結構(定義)
2.delete語句是dml,這個操作會放到rollback segement中,事務提交之后才生效;如果有相應的trigger,執行的時候將被觸發.
truncate是ddl, 操作立即生效,原數據不放到rollback segment中,不能回滾. 操作不觸發trigger.
3.delete語句不影響表所占用的extent, 高水線(high watermark)保持原位置不動
顯然drop語句將表所占用的空間全部釋放
truncate 語句缺省情況下見空間釋放到 minextents個 extent,除非使用reuse storage; truncate 會將高水線復位(回到最開始).
4.速度,一般來說: truncate > delete
5.安全性:小心使用drop 和truncate,尤其沒有備份的時候.否則哭都來不及.
使用上,想刪除部分數據行用delete,注意帶上where子句. 回滾段要足夠大.
想保留表而將所有數據刪除. 如果和事務無關,用truncate即可. 如果和事務有關,或者想觸發trigger,還是用delete.
如果是整理表內部的碎片,可以用truncate跟上reuse stroage,再重新導入/插入數據/