前言
Goal, learn index.
Next, do some basic data first.
- First create a table (note that id is not a primary key)
DROP TABLE IF EXISTS `test_indexes`; CREATE TABLE `test_indexes` ( `id` int NOT NULL, `c1` varchar(255) DEFAULT NULL, `c2` varchar(255) DEFAULT NULL, `c3` varchar(255) DEFAULT NULL, `c4` varchar(255) DEFAULT NULL, `c5` varchar(255) DEFAULT NULL, `c6` varchar(255) DEFAULT NULL, `c7` varchar(255) DEFAULT NULL, `c8` varchar(255) DEFAULT NULL, `c9` varchar(255) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
- Then, insert the data,
insert the data we passStored procedureGo to insert. (The simple application of the stored procedure will be specially organized later)
Select the function-right click to add-select the process, add and save
BEGIN declare i int default 1; start transaction; #开启事务 while i <= 1000000 do insert into test_indexes values(i, concat("张天爱-", i), '测试字段', '测试字段', '测试字段', '测试字段', '测试字段', '测试字段', '测试字段', '测试字段'); set i = i+1; end while; commit; END
开始测试
- Test query data
directly select * query, found that it can not be found at all, it takes half a day to display a part;
Then search by page, you can find out normallyselect * from test_indexes
select * from test_indexes order by id desc limit 0,10
- Test to add a unique index to the id
Because there is too much data, it only took more than ten seconds to add an index to the table.
After adding it, let's try the paging query again.
You can see that the same statement takes1.356
seconds without adding an index.
After adding a unique index, it takes0.031
seconds, not even 0.1 seconds.
测试条件查询
The c1 field did not add an index, and the query time took 0.706
seconds.
The following test adds a normal index to the c1 field.
Test again.
You can see that it only took 0.034
seconds! This is a huge improvement.
总结
I didn’t know it before, I found it difficult and complicated. After I tried it, I found it was very useful.
But when inserting and updating, it will be modified to the index, so the index cannot be added too much, otherwise it will reduce the speed of editing.
Various types of indexes will be added later.