[Mysql] sql optimized learning index (1)

前言

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
    Insert picture description here
    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
    
    Insert picture description here

开始测试

  • Test query data
    directly select * query, found that it can not be found at all, it takes half a day to display a part;
    select * from test_indexes
    
    Then search by page, you can find out normally
    select * from test_indexes order by id desc limit 0,10
    
    Insert picture description here
  1. 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.
    Insert picture description here
    You can see that the same statement takes 1.356seconds without adding an index.
    After adding a unique index, it takes 0.031seconds, not even 0.1 seconds.

测试条件查询

The c1 field did not add an index, and the query time took 0.706seconds.
Insert picture description here
The following test adds a normal index to the c1 field.
Insert picture description here
Test again.
Insert picture description here
You can see that it only took 0.034seconds! 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.

Guess you like

Origin blog.csdn.net/s1441101265/article/details/114980854