目錄
- 前言
- Innodb表空間
- Inndob存儲(chǔ)分布
- 創(chuàng)建空表查看空間變化
- 插入數(shù)據(jù)后的空間變化
- delete數(shù)據(jù)后的空間變化
- Innodb中的碎片
- delete對(duì)SQL的影響
- 未刪除前的SQL執(zhí)行情況
- 刪除后的SQL執(zhí)行情況
- delete優(yōu)化建議
- 控制業(yè)務(wù)賬號(hào)權(quán)限
- delete改為標(biāo)記刪除
- 數(shù)據(jù)歸檔方式
- 通用數(shù)據(jù)歸檔方法
- 優(yōu)化后的歸檔方式
- 總結(jié)
前言
我負(fù)責(zé)的有幾個(gè)系統(tǒng)隨著業(yè)務(wù)量的增長(zhǎng),存儲(chǔ)在MySQL中的數(shù)據(jù)日益劇增,我當(dāng)時(shí)就想現(xiàn)在的業(yè)務(wù)方不講武德,搞偷襲,趁我沒反應(yīng)過來把很多表,很快,很快啊都打到了億級(jí)別,我大意了,沒有閃,這就導(dǎo)致跟其Join的表的SQL變得很慢,對(duì)的應(yīng)用接口的response time也變長(zhǎng)了,影響了用戶體驗(yàn)。
事后我找到業(yè)務(wù)方,我批評(píng)了他們跟他們說要講武德,連忙跟我道歉,這個(gè)事情才就此作罷,走的時(shí)候我對(duì)他們說下次不要這樣了,耗子尾汁,好好反思。
罵歸罵,事情還是得解決,時(shí)候我分析原因發(fā)現(xiàn),發(fā)現(xiàn)有些表的數(shù)據(jù)量增長(zhǎng)很快,對(duì)應(yīng)SQL掃描了很多無效數(shù)據(jù),導(dǎo)致SQL慢了下來,通過確認(rèn)之后,這些大表都是一些流水、記錄、日志類型數(shù)據(jù),只需要保留1到3個(gè)月,此時(shí)需要對(duì)表做數(shù)據(jù)清理實(shí)現(xiàn)瘦身,一般都會(huì)想到用insert + delete的方式去清理。
這篇文章我會(huì)從InnoDB存儲(chǔ)空間分布,delete對(duì)性能的影響,以及優(yōu)化建議方面解釋為什么不建議delete刪除數(shù)據(jù)。
InnoDB存儲(chǔ)架構(gòu)
從這張圖可以看到,InnoDB存儲(chǔ)結(jié)構(gòu)主要包括兩部分:邏輯存儲(chǔ)結(jié)構(gòu)和物理存儲(chǔ)結(jié)構(gòu)。
邏輯上是由表空間tablespace —> 段segment或者inode —> 區(qū)Extent ——>數(shù)據(jù)頁P(yáng)age構(gòu)成,Innodb邏輯管理單位是segment,空間分配的最小單位是extent,每個(gè)segment都會(huì)從表空間FREE_PAGE中分配32個(gè)page,當(dāng)這32個(gè)page不夠用時(shí),會(huì)按照以下原則進(jìn)行擴(kuò)展:如果當(dāng)前小于1個(gè)extent,則擴(kuò)展到1個(gè)extent;當(dāng)表空間小于32MB時(shí),每次擴(kuò)展一個(gè)extent;表空間大于32MB,每次擴(kuò)展4個(gè)extent。
物理上主要由系統(tǒng)用戶數(shù)據(jù)文件,日志文件組成,數(shù)據(jù)文件主要存儲(chǔ)MySQL字典數(shù)據(jù)和用戶數(shù)據(jù),日志文件記錄的是data page的變更記錄,用于MySQL Crash時(shí)的恢復(fù)。
Innodb表空間
InnoDB存儲(chǔ)包括三類表空間:系統(tǒng)表空間,用戶表空間,Undo表空間。
**系統(tǒng)表空間:**主要存儲(chǔ)MySQL內(nèi)部的數(shù)據(jù)字典數(shù)據(jù),如information_schema下的數(shù)據(jù)。
**用戶表空間:**當(dāng)開啟innodb_file_per_table=1時(shí),數(shù)據(jù)表從系統(tǒng)表空間獨(dú)立出來存儲(chǔ)在以table_name.ibd命令的數(shù)據(jù)文件中,結(jié)構(gòu)信息存儲(chǔ)在table_name.frm文件中。
**Undo表空間:**存儲(chǔ)Undo信息,如快照一致讀和flashback都是利用undo信息。
從MySQL 8.0開始允許用戶自定義表空間,具體語法如下:
CREATE TABLESPACE tablespace_name
ADD DATAFILE 'file_name' #數(shù)據(jù)文件名
USE LOGFILE GROUP logfile_group #自定義日志文件組,一般每組2個(gè)logfile。
[EXTENT_SIZE [=] extent_size] #區(qū)大小
[INITIAL_SIZE [=] initial_size] #初始化大小
[AUTOEXTEND_SIZE [=] autoextend_size] #自動(dòng)擴(kuò)寬尺寸
[MAX_SIZE [=] max_size] #單個(gè)文件最大size,最大是32G。
[NODEGROUP [=] nodegroup_id] #節(jié)點(diǎn)組
[WAIT]
[COMMENT [=] comment_text]
ENGINE [=] engine_name
這樣的好處是可以做到數(shù)據(jù)的冷熱分離,分別用HDD和SSD來存儲(chǔ),既能實(shí)現(xiàn)數(shù)據(jù)的高效訪問,又能節(jié)約成本,比如可以添加兩塊500G硬盤,經(jīng)過創(chuàng)建卷組vg,劃分邏輯卷lv,創(chuàng)建數(shù)據(jù)目錄并mount相應(yīng)的lv,假設(shè)劃分的兩個(gè)目錄分別是/hot_data 和 /cold_data。
這樣就可以將核心的業(yè)務(wù)表如用戶表,訂單表存儲(chǔ)在高性能SSD盤上,一些日志,流水表存儲(chǔ)在普通的HDD上,主要的操作步驟如下:
#創(chuàng)建熱數(shù)據(jù)表空間
create tablespace tbs_data_hot add datafile '/hot_data/tbs_data_hot01.dbf' max_size 20G;
#創(chuàng)建核心業(yè)務(wù)表存儲(chǔ)在熱數(shù)據(jù)表空間
create table booking(id bigint not null primary key auto_increment, …… ) tablespace tbs_data_hot;
#創(chuàng)建冷數(shù)據(jù)表空間
create tablespace tbs_data_cold add datafile '/hot_data/tbs_data_cold01.dbf' max_size 20G;
#創(chuàng)建日志,流水,備份類的表存儲(chǔ)在冷數(shù)據(jù)表空間
create table payment_log(id bigint not null primary key auto_increment, …… ) tablespace tbs_data_cold;
#可以移動(dòng)表到另一個(gè)表空間
alter table payment_log tablespace tbs_data_hot;
Inndob存儲(chǔ)分布
創(chuàng)建空表查看空間變化
mysql> create table user(id bigint not null primary key auto_increment,
-> name varchar(20) not null default '' comment '姓名',
-> age tinyint not null default 0 comment 'age',
-> gender char(1) not null default 'M' comment '性別',
-> phone varchar(16) not null default '' comment '手機(jī)號(hào)',
-> create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時(shí)間',
-> update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改時(shí)間'
-> ) engine = InnoDB DEFAULT CHARSET=utf8mb4 COMMENT '用戶信息表';
Query OK, 0 rows affected (0.26 sec)
# ls -lh user1.ibd
-rw-r----- 1 mysql mysql 96K Nov 6 12:48 user.ibd
設(shè)置參數(shù)innodb_file_per_table=1時(shí),創(chuàng)建表時(shí)會(huì)自動(dòng)創(chuàng)建一個(gè)segment,同時(shí)分配一個(gè)extent,包含32個(gè)data page的來存儲(chǔ)數(shù)據(jù),這樣創(chuàng)建的空表默認(rèn)大小就是96KB,extent使用完之后會(huì)申請(qǐng)64個(gè)連接頁,這樣對(duì)于一些小表,或者undo segment,可以在開始時(shí)申請(qǐng)較少的空間,節(jié)省磁盤容量的開銷。
# python2 py_innodb_page_info.py -v /data2/mysql/test/user.ibd
page offset 00000000, page type File Space Header>
page offset 00000001, page type Insert Buffer Bitmap>
page offset 00000002, page type File Segment inode>
page offset 00000003, page type B-tree Node>, page level 0000>
page offset 00000000, page type Freshly Allocated Page>
page offset 00000000, page type Freshly Allocated Page>
Total number of page: 6: #總共分配的頁數(shù)
Freshly Allocated Page: 2 #可用的數(shù)據(jù)頁
Insert Buffer Bitmap: 1 #插入緩沖頁
File Space Header: 1 #文件空間頭
B-tree Node: 1 #數(shù)據(jù)頁
File Segment inode: 1 #文件端inonde,如果是在ibdata1.ibd上會(huì)有多個(gè)inode。
插入數(shù)據(jù)后的空間變化
mysql> DELIMITER $$
mysql> CREATE PROCEDURE insert_user_data(num INTEGER)
-> BEGIN
-> DECLARE v_i int unsigned DEFAULT 0;
-> set autocommit= 0;
-> WHILE v_i num DO
-> insert into user(`name`, age, gender, phone) values (CONCAT('lyn',v_i), mod(v_i,120), 'M', CONCAT('152',ROUND(RAND(1)*100000000)));
-> SET v_i = v_i+1;
-> END WHILE;
-> commit;
-> END $$
Query OK, 0 rows affected (0.01 sec)
mysql> DELIMITER ;
#插入10w數(shù)據(jù)
mysql> call insert_user_data(100000);
Query OK, 0 rows affected (6.69 sec)
# ls -lh user.ibd
-rw-r----- 1 mysql mysql 14M Nov 6 10:58 /data2/mysql/test/user.ibd
# python2 py_innodb_page_info.py -v /data2/mysql/test/user.ibd
page offset 00000000, page type File Space Header>
page offset 00000001, page type Insert Buffer Bitmap>
page offset 00000002, page type File Segment inode>
page offset 00000003, page type B-tree Node>, page level 0001> #增加了一個(gè)非葉子節(jié)點(diǎn),樹的高度從1變?yōu)?.
........................................................
page offset 00000000, page type Freshly Allocated Page>
Total number of page: 896:
Freshly Allocated Page: 493
Insert Buffer Bitmap: 1
File Space Header: 1
B-tree Node: 400
File Segment inode: 1
delete數(shù)據(jù)后的空間變化
mysql> select min(id),max(id),count(*) from user;
+---------+---------+----------+
| min(id) | max(id) | count(*) |
+---------+---------+----------+
| 1 | 100000 | 100000 |
+---------+---------+----------+
1 row in set (0.05 sec)
#刪除50000條數(shù)據(jù),理論上空間應(yīng)該從14MB變長(zhǎng)7MB左右。
mysql> delete from user limit 50000;
Query OK, 50000 rows affected (0.25 sec)
#數(shù)據(jù)文件大小依然是14MB,沒有縮小。
# ls -lh /data2/mysql/test/user1.ibd
-rw-r----- 1 mysql mysql 14M Nov 6 13:22 /data2/mysql/test/user.ibd
#數(shù)據(jù)頁沒有被回收。
# python2 py_innodb_page_info.py -v /data2/mysql/test/user.ibd
page offset 00000000, page type File Space Header>
page offset 00000001, page type Insert Buffer Bitmap>
page offset 00000002, page type File Segment inode>
page offset 00000003, page type B-tree Node>, page level 0001>
........................................................
page offset 00000000, page type Freshly Allocated Page>
Total number of page: 896:
Freshly Allocated Page: 493
Insert Buffer Bitmap: 1
File Space Header: 1
B-tree Node: 400
File Segment inode: 1
#在MySQL內(nèi)部是標(biāo)記刪除,
mysql> use information_schema;
Database changed
mysql> SELECT A.SPACE AS TBL_SPACEID, A.TABLE_ID, A.NAME AS TABLE_NAME, FILE_FORMAT, ROW_FORMAT, SPACE_TYPE, B.INDEX_ID , B.NAME AS INDEX_NAME, PAGE_NO, B.TYPE AS INDEX_TYPE FROM INNODB_SYS_TABLES A LEFT JOIN INNODB_SYS_INDEXES B ON A.TABLE_ID =B.TABLE_ID WHERE A.NAME = 'test/user1';
+-------------+----------+------------+-------------+------------+------------+----------+------------+---------+------------+
| TBL_SPACEID | TABLE_ID | TABLE_NAME | FILE_FORMAT | ROW_FORMAT | SPACE_TYPE | INDEX_ID | INDEX_NAME | PAGE_NO | INDEX_TYPE |
+-------------+----------+------------+-------------+------------+------------+----------+------------+---------+------------+
| 1283 | 1207 | test/user | Barracuda | Dynamic | Single | 2236 | PRIMARY | 3 | 3 |
+-------------+----------+------------+-------------+------------+------------+----------+------------+---------+------------+
1 row in set (0.01 sec)
PAGE_NO = 3 標(biāo)識(shí)B-tree的root page是3號(hào)頁,INDEX_TYPE = 3是聚集索引。 INDEX_TYPE取值如下:
0 = nonunique secondary index;
1 = automatically generated clustered index (GEN_CLUST_INDEX);
2 = unique nonclustered index;
3 = clustered index;
32 = full-text index;
#收縮空間再后進(jìn)行觀察
MySQL內(nèi)部不會(huì)真正刪除空間,而且做標(biāo)記刪除,即將delflag:N修改為delflag:Y,commit之后會(huì)會(huì)被purge進(jìn)入刪除鏈表,如果下一次insert更大的記錄,delete之后的空間不會(huì)被重用,如果插入的記錄小于等于delete的記錄空會(huì)被重用,這塊內(nèi)容可以通過知數(shù)堂的innblock工具進(jìn)行分析。
Innodb中的碎片
碎片的產(chǎn)生
我們知道數(shù)據(jù)存儲(chǔ)在文件系統(tǒng)上的,總是不能100%利用分配給它的物理空間,刪除數(shù)據(jù)會(huì)在頁面上留下一些”空洞”,或者隨機(jī)寫入(聚集索引非線性增加)會(huì)導(dǎo)致頁分裂,頁分裂導(dǎo)致頁面的利用空間少于50%,另外對(duì)表進(jìn)行增刪改會(huì)引起對(duì)應(yīng)的二級(jí)索引值的隨機(jī)的增刪改,也會(huì)導(dǎo)致索引結(jié)構(gòu)中的數(shù)據(jù)頁面上留下一些"空洞",雖然這些空洞有可能會(huì)被重復(fù)利用,但終究會(huì)導(dǎo)致部分物理空間未被使用,也就是碎片。
同時(shí),即便是設(shè)置了填充因子為100%,Innodb也會(huì)主動(dòng)留下page頁面1/16的空間作為預(yù)留使用(An innodb_fill_factor setting of 100 leaves 1/16 of the space in clustered index pages free for future index growth)防止update帶來的行溢出。
mysql> select table_schema,
-> table_name,ENGINE,
-> round(DATA_LENGTH/1024/1024+ INDEX_LENGTH/1024/1024) total_mb,TABLE_ROWS,
-> round(DATA_LENGTH/1024/1024) data_mb, round(INDEX_LENGTH/1024/1024) index_mb, round(DATA_FREE/1024/1024) free_mb, round(DATA_FREE/DATA_LENGTH*100,2) free_ratio
-> from information_schema.TABLES where TABLE_SCHEMA= 'test'
-> and TABLE_NAME= 'user';
+--------------+------------+--------+----------+------------+---------+----------+---------+------------+
| table_schema | table_name | ENGINE | total_mb | TABLE_ROWS | data_mb | index_mb | free_mb | free_ratio |
+--------------+------------+--------+----------+------------+---------+----------+---------+------------+
| test | user | InnoDB | 4 | 50000 | 4 | 0 | 6 | 149.42 |
+--------------+------------+--------+----------+------------+---------+----------+---------+------------+
1 row in set (0.00 sec)
其中data_free是分配了未使用的字節(jié)數(shù),并不能說明完全是碎片空間。
碎片的回收
對(duì)于InnoDB的表,可以通過以下命令來回收碎片,釋放空間,這個(gè)是隨機(jī)讀IO操作,會(huì)比較耗時(shí),也會(huì)阻塞表上正常的DML運(yùn)行,同時(shí)需要占用額外更多的磁盤空間,對(duì)于RDS來說,可能會(huì)導(dǎo)致磁盤空間瞬間爆滿,實(shí)例瞬間被鎖定,應(yīng)用無法做DML操作,所以禁止在線上環(huán)境去執(zhí)行。
#執(zhí)行InnoDB的碎片回收
mysql> alter table user engine=InnoDB;
Query OK, 0 rows affected (9.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
##執(zhí)行完之后,數(shù)據(jù)文件大小從14MB降低到10M。
# ls -lh /data2/mysql/test/user1.ibd
-rw-r----- 1 mysql mysql 10M Nov 6 16:18 /data2/mysql/test/user.ibd
mysql> select table_schema, table_name,ENGINE, round(DATA_LENGTH/1024/1024+ INDEX_LENGTH/1024/1024) total_mb,TABLE_ROWS, round(DATA_LENGTH/1024/1024) data_mb, round(INDEX_LENGTH/1024/1024) index_mb, round(DATA_FREE/1024/1024) free_mb, round(DATA_FREE/DATA_LENGTH*100,2) free_ratio from information_schema.TABLES where TABLE_SCHEMA= 'test' and TABLE_NAME= 'user';
+--------------+------------+--------+----------+------------+---------+----------+---------+------------+
| table_schema | table_name | ENGINE | total_mb | TABLE_ROWS | data_mb | index_mb | free_mb | free_ratio |
+--------------+------------+--------+----------+------------+---------+----------+---------+------------+
| test | user | InnoDB | 5 | 50000 | 5 | 0 | 2 | 44.29 |
+--------------+------------+--------+----------+------------+---------+----------+---------+------------+
1 row in set (0.00 sec)
delete對(duì)SQL的影響
未刪除前的SQL執(zhí)行情況
#插入100W數(shù)據(jù)
mysql> call insert_user_data(1000000);
Query OK, 0 rows affected (35.99 sec)
#添加相關(guān)索引
mysql> alter table user add index idx_name(name), add index idx_phone(phone);
Query OK, 0 rows affected (6.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
#表上索引統(tǒng)計(jì)信息
mysql> show index from user;
+-------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| user | 0 | PRIMARY | 1 | id | A | 996757 | NULL | NULL | | BTREE | | |
| user | 1 | idx_name | 1 | name | A | 996757 | NULL | NULL | | BTREE | | |
| user | 1 | idx_phone | 1 | phone | A | 2 | NULL | NULL | | BTREE | | |
+-------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
3 rows in set (0.00 sec)
#重置狀態(tài)變量計(jì)數(shù)
mysql> flush status;
Query OK, 0 rows affected (0.00 sec)
#執(zhí)行SQL語句
mysql> select id, age ,phone from user where name like 'lyn12%';
+--------+-----+-------------+
| id | age | phone |
+--------+-----+-------------+
| 124 | 3 | 15240540354 |
| 1231 | 30 | 15240540354 |
| 12301 | 60 | 15240540354 |
.............................
| 129998 | 37 | 15240540354 |
| 129999 | 38 | 15240540354 |
| 130000 | 39 | 15240540354 |
+--------+-----+-------------+
11111 rows in set (0.03 sec)
mysql> explain select id, age ,phone from user where name like 'lyn12%';
+----+-------------+-------+-------+---------------+----------+---------+------+-------+-----------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+----------+---------+------+-------+-----------------------+
| 1 | SIMPLE | user | range | idx_name | idx_name | 82 | NULL | 22226 | Using index condition |
+----+-------------+-------+-------+---------------+----------+---------+------+-------+-----------------------+
1 row in set (0.00 sec)
#查看相關(guān)狀態(tài)呢變量
mysql> select * from information_schema.session_status where variable_name in('Last_query_cost','Handler_read_next','Innodb_pages_read','Innodb_data_reads','Innodb_pages_read');
+-------------------+----------------+
| VARIABLE_NAME | VARIABLE_VALUE |
+-------------------+----------------+
| HANDLER_READ_NEXT | 11111 | #請(qǐng)求讀的行數(shù)
| INNODB_DATA_READS | 7868409 | #數(shù)據(jù)物理讀的總數(shù)
| INNODB_PAGES_READ | 7855239 | #邏輯讀的總數(shù)
| LAST_QUERY_COST | 10.499000 | #SQL語句的成本COST,主要包括IO_COST和CPU_COST。
+-------------------+----------------+
4 rows in set (0.00 sec)
刪除后的SQL執(zhí)行情況
#刪除50w數(shù)據(jù)
mysql> delete from user limit 500000;
Query OK, 500000 rows affected (3.70 sec)
#分析表統(tǒng)計(jì)信息
mysql> analyze table user;
+-----------+---------+----------+----------+
| Table | Op | Msg_type | Msg_text |
+-----------+---------+----------+----------+
| test.user | analyze | status | OK |
+-----------+---------+----------+----------+
1 row in set (0.01 sec)
#重置狀態(tài)變量計(jì)數(shù)
mysql> flush status;
Query OK, 0 rows affected (0.01 sec)
mysql> select id, age ,phone from user where name like 'lyn12%';
Empty set (0.05 sec)
mysql> explain select id, age ,phone from user where name like 'lyn12%';
+----+-------------+-------+-------+---------------+----------+---------+------+-------+-----------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+----------+---------+------+-------+-----------------------+
| 1 | SIMPLE | user | range | idx_name | idx_name | 82 | NULL | 22226 | Using index condition |
+----+-------------+-------+-------+---------------+----------+---------+------+-------+-----------------------+
1 row in set (0.00 sec)
mysql> select * from information_schema.session_status where variable_name in('Last_query_cost','Handler_read_next','Innodb_pages_read','Innodb_data_reads','Innodb_pages_read');
+-------------------+----------------+
| VARIABLE_NAME | VARIABLE_VALUE |
+-------------------+----------------+
| HANDLER_READ_NEXT | 0 |
| INNODB_DATA_READS | 7868409 |
| INNODB_PAGES_READ | 7855239 |
| LAST_QUERY_COST | 10.499000 |
+-------------------+----------------+
4 rows in set (0.00 sec)
結(jié)果統(tǒng)計(jì)分析
操作 |
COST |
物理讀次數(shù) |
邏輯讀次數(shù) |
掃描行數(shù) |
返回行數(shù) |
執(zhí)行時(shí)間 |
初始化插入100W |
10.499000 |
7868409 |
7855239 |
22226 |
11111 |
30ms |
100W隨機(jī)刪除50W |
10.499000 |
7868409 |
7855239 |
22226 |
0 |
50ms |
這也說明對(duì)普通的大表,想要通過delete數(shù)據(jù)來對(duì)表進(jìn)行瘦身是不現(xiàn)實(shí)的,所以在任何時(shí)候不要用delete去刪除數(shù)據(jù),應(yīng)該使用優(yōu)雅的標(biāo)記刪除。
delete優(yōu)化建議
控制業(yè)務(wù)賬號(hào)權(quán)限
對(duì)于一個(gè)大的系統(tǒng)來說,需要根據(jù)業(yè)務(wù)特點(diǎn)去拆分子系統(tǒng),每個(gè)子系統(tǒng)可以看做是一個(gè)service,例如美團(tuán)APP,上面有很多服務(wù),核心的服務(wù)有用戶服務(wù)user-service,搜索服務(wù)search-service,商品product-service,位置服務(wù)location-service,價(jià)格服務(wù)price-service等。每個(gè)服務(wù)對(duì)應(yīng)一個(gè)數(shù)據(jù)庫(kù),為該數(shù)據(jù)庫(kù)創(chuàng)建單獨(dú)賬號(hào),同時(shí)只授予DML權(quán)限且沒有delete權(quán)限,同時(shí)禁止跨庫(kù)訪問。
#創(chuàng)建用戶數(shù)據(jù)庫(kù)并授權(quán)
create database mt_user charset utf8mb4;
grant USAGE, SELECT, INSERT, UPDATE ON mt_user.* to 'w_user'@'%' identified by 't$W*g@gaHTGi123456';
flush privileges;
delete改為標(biāo)記刪除
在MySQL數(shù)據(jù)庫(kù)建模規(guī)范中有4個(gè)公共字段,基本上每個(gè)表必須有的,同時(shí)在create_time列要?jiǎng)?chuàng)建索引,有兩方面的好處:
- 一些查詢業(yè)務(wù)場(chǎng)景都會(huì)有一個(gè)默認(rèn)的時(shí)間段,比如7天或者一個(gè)月,都是通過create_time去過濾,走索引掃描更快。
- 一些核心的業(yè)務(wù)表需要以T +1的方式抽取數(shù)據(jù)倉(cāng)庫(kù)中,比如每天晚上00:30抽取前一天的數(shù)據(jù),都是通過create_time過濾的。
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵id',
`is_deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否邏輯刪除:0:未刪除,1:已刪除',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時(shí)間',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改時(shí)間'
#有了刪除標(biāo)記,業(yè)務(wù)接口的delete操作就可以轉(zhuǎn)換為update
update user set is_deleted = 1 where user_id = 1213;
#查詢的時(shí)候需要帶上is_deleted過濾
select id, age ,phone from user where is_deleted = 0 and name like 'lyn12%';
數(shù)據(jù)歸檔方式
通用數(shù)據(jù)歸檔方法
#1. 創(chuàng)建歸檔表,一般在原表名后面添加_bak。
CREATE TABLE `ota_order_bak` (
`id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
`order_id` varchar(255) DEFAULT NULL COMMENT '訂單id',
`ota_id` varchar(255) DEFAULT NULL COMMENT 'ota',
`check_in_date` varchar(255) DEFAULT NULL COMMENT '入住日期',
`check_out_date` varchar(255) DEFAULT NULL COMMENT '離店日期',
`hotel_id` varchar(255) DEFAULT NULL COMMENT '酒店ID',
`guest_name` varchar(255) DEFAULT NULL COMMENT '顧客',
`purcharse_time` timestamp NULL DEFAULT NULL COMMENT '購(gòu)買時(shí)間',
`create_time` datetime DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`create_user` varchar(255) DEFAULT NULL,
`update_user` varchar(255) DEFAULT NULL,
`status` int(4) DEFAULT '1' COMMENT '狀態(tài) : 1 正常 , 0 刪除',
`hotel_name` varchar(255) DEFAULT NULL,
`price` decimal(10,0) DEFAULT NULL,
`remark` longtext,
PRIMARY KEY (`id`),
KEY `IDX_order_id` (`order_id`) USING BTREE,
KEY `hotel_name` (`hotel_name`) USING BTREE,
KEY `ota_id` (`ota_id`) USING BTREE,
KEY `IDX_purcharse_time` (`purcharse_time`) USING BTREE,
KEY `IDX_create_time` (`create_time`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8
PARTITION BY RANGE (to_days(create_time)) (
PARTITION p201808 VALUES LESS THAN (to_days('2018-09-01')),
PARTITION p201809 VALUES LESS THAN (to_days('2018-10-01')),
PARTITION p201810 VALUES LESS THAN (to_days('2018-11-01')),
PARTITION p201811 VALUES LESS THAN (to_days('2018-12-01')),
PARTITION p201812 VALUES LESS THAN (to_days('2019-01-01')),
PARTITION p201901 VALUES LESS THAN (to_days('2019-02-01')),
PARTITION p201902 VALUES LESS THAN (to_days('2019-03-01')),
PARTITION p201903 VALUES LESS THAN (to_days('2019-04-01')),
PARTITION p201904 VALUES LESS THAN (to_days('2019-05-01')),
PARTITION p201905 VALUES LESS THAN (to_days('2019-06-01')),
PARTITION p201906 VALUES LESS THAN (to_days('2019-07-01')),
PARTITION p201907 VALUES LESS THAN (to_days('2019-08-01')),
PARTITION p201908 VALUES LESS THAN (to_days('2019-09-01')),
PARTITION p201909 VALUES LESS THAN (to_days('2019-10-01')),
PARTITION p201910 VALUES LESS THAN (to_days('2019-11-01')),
PARTITION p201911 VALUES LESS THAN (to_days('2019-12-01')),
PARTITION p201912 VALUES LESS THAN (to_days('2020-01-01')));
#2. 插入原表中無效的數(shù)據(jù)(需要跟開發(fā)同學(xué)確認(rèn)數(shù)據(jù)保留范圍)
create table tbl_p201808 as select * from ota_order where create_time between '2018-08-01 00:00:00' and '2018-08-31 23:59:59';
#3. 跟歸檔表分區(qū)做分區(qū)交換
alter table ota_order_bak exchange partition p201808 with table tbl_p201808;
#4. 刪除原表中已經(jīng)規(guī)范的數(shù)據(jù)
delete from ota_order where create_time between '2018-08-01 00:00:00' and '2018-08-31 23:59:59' limit 3000;
優(yōu)化后的歸檔方式
#1. 創(chuàng)建中間表
CREATE TABLE `ota_order_2020` (........) ENGINE=InnoDB DEFAULT CHARSET=utf8
PARTITION BY RANGE (to_days(create_time)) (
PARTITION p201808 VALUES LESS THAN (to_days('2018-09-01')),
PARTITION p201809 VALUES LESS THAN (to_days('2018-10-01')),
PARTITION p201810 VALUES LESS THAN (to_days('2018-11-01')),
PARTITION p201811 VALUES LESS THAN (to_days('2018-12-01')),
PARTITION p201812 VALUES LESS THAN (to_days('2019-01-01')),
PARTITION p201901 VALUES LESS THAN (to_days('2019-02-01')),
PARTITION p201902 VALUES LESS THAN (to_days('2019-03-01')),
PARTITION p201903 VALUES LESS THAN (to_days('2019-04-01')),
PARTITION p201904 VALUES LESS THAN (to_days('2019-05-01')),
PARTITION p201905 VALUES LESS THAN (to_days('2019-06-01')),
PARTITION p201906 VALUES LESS THAN (to_days('2019-07-01')),
PARTITION p201907 VALUES LESS THAN (to_days('2019-08-01')),
PARTITION p201908 VALUES LESS THAN (to_days('2019-09-01')),
PARTITION p201909 VALUES LESS THAN (to_days('2019-10-01')),
PARTITION p201910 VALUES LESS THAN (to_days('2019-11-01')),
PARTITION p201911 VALUES LESS THAN (to_days('2019-12-01')),
PARTITION p201912 VALUES LESS THAN (to_days('2020-01-01')));
#2. 插入原表中有效的數(shù)據(jù),如果數(shù)據(jù)量在100W左右可以在業(yè)務(wù)低峰期直接插入,如果比較大,建議采用dataX來做,可以控制頻率和大小,之前我這邊用Go封裝了dataX可以實(shí)現(xiàn)自動(dòng)生成json文件,自定義大小去執(zhí)行。
insert into ota_order_2020 select * from ota_order where create_time between '2020-08-01 00:00:00' and '2020-08-31 23:59:59';
#3. 表重命名
alter table ota_order rename to ota_order_bak;
alter table ota_order_2020 rename to ota_order;
#4. 插入差異數(shù)據(jù)
insert into ota_order select * from ota_order_bak a where not exists (select 1 from ota_order b where a.id = b.id);
#5. ota_order_bak改造成分區(qū)表,如果表比較大不建議直接改造,可以先創(chuàng)建好分區(qū)表,通過dataX把導(dǎo)入進(jìn)去即可。
#6. 后續(xù)的歸檔方法
#創(chuàng)建中間普遍表
create table ota_order_mid like ota_order;
#交換原表無效數(shù)據(jù)分區(qū)到普通表
alter table ota_order exchange partition p201808 with table ota_order_mid;
##交換普通表數(shù)據(jù)到歸檔表的相應(yīng)分區(qū)
alter table ota_order_bak exchange partition p201808 with table ota_order_mid;
這樣原表和歸檔表都是按月的分區(qū)表,只需要?jiǎng)?chuàng)建一個(gè)中間普通表,在業(yè)務(wù)低峰期做兩次分區(qū)交換,既可以刪除無效數(shù)據(jù),又能回收空,而且沒有空間碎片,不會(huì)影響表上的索引及SQL的執(zhí)行計(jì)劃。
總結(jié)
通過從InnoDB存儲(chǔ)空間分布,delete對(duì)性能的影響可以看到,delete物理刪除既不能釋放磁盤空間,而且會(huì)產(chǎn)生大量的碎片,導(dǎo)致索引頻繁分裂,影響SQL執(zhí)行計(jì)劃的穩(wěn)定性;
同時(shí)在碎片回收時(shí),會(huì)耗用大量的CPU,磁盤空間,影響表上正常的DML操作。
在業(yè)務(wù)代碼層面,應(yīng)該做邏輯標(biāo)記刪除,避免物理刪除;為了實(shí)現(xiàn)數(shù)據(jù)歸檔需求,可以用采用MySQL分區(qū)表特性來實(shí)現(xiàn),都是DDL操作,沒有碎片產(chǎn)生。
另外一個(gè)比較好的方案采用Clickhouse,對(duì)有生命周期的數(shù)據(jù)表可以使用Clickhouse存儲(chǔ),利用其TTL特性實(shí)現(xiàn)無效數(shù)據(jù)自動(dòng)清理。
到此這篇關(guān)于淺談為什么MySQL不建議delete刪除數(shù)據(jù)的文章就介紹到這了,更多相關(guān)MySQL不建議delete刪除內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- MyBatis批量插入/修改/刪除MySql數(shù)據(jù)
- mysql利用mysqlbinlog命令恢復(fù)誤刪除數(shù)據(jù)的實(shí)現(xiàn)
- mysql5.7.33誤刪除ibdata文件找回?cái)?shù)據(jù)的方法
- mysql數(shù)據(jù)庫(kù)刪除重復(fù)數(shù)據(jù)只保留一條方法實(shí)例
- mysql 大表批量刪除大量數(shù)據(jù)的實(shí)現(xiàn)方法
- Python批量刪除mysql中千萬級(jí)大量數(shù)據(jù)的腳本分享
- Mysql刪除數(shù)據(jù)以及數(shù)據(jù)表的方法實(shí)例
- MySQL刪除數(shù)據(jù),表文件大小依然沒變的原因
- MySQL 快速刪除大量數(shù)據(jù)(千萬級(jí)別)的幾種實(shí)踐方案詳解
- MySQL Delete 刪數(shù)據(jù)后磁盤空間未釋放的原因