Database index operation bitsCN.com
Database index operations
I have never used indexes before and have never realized the benefits of indexes. a few days ago, I had to process tables with millions of records. for example, if there were too many records for queries on both sides, the query speed was quite slow, so I tried to use the index and found that the speed improvement was not a little bit, but a lot of points.
The procedure is as follows:
1. create two tables first, as shown in:
The table creation statement is as follows:
[sql] CREATE TABLE `t1` ( `ID` bigint(20) NOT NULL AUTO_INCREMENT, `Num` int(11) NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Table 2 and Table 1 are created in a similar way.
2. fill data in the two tables and use the stored procedure as follows:
The above is the interface for creating a stored procedure with navicat. create two stored procedures and fill data in t1 and t2 respectively. the code is as follows:
Storage process for filling t1
[SQL] BEGIN # Routine body goes here... declare n int; set n = 1; while n <= 50000 do insert into t1 (Num) values (n); set n = n + 1; end while; storage process of END filling t2 [SQL] BEGIN # Routine body goes here... declare n int; set n = 1; while n <= 25000 do insert into t2 (Num) values (n); set n = n + 1; end while; set n = 1; while n <= 25000 do insert into t2 (Num) values (0); set n = n + 1; end while; END
III. join table query
Calculate the number of rows with the same Num field in the two tables. the query statement is as follows:
[sql] select count(*) from t1,t2 where t1.Num = t1.Num;
Each line of t1 needs to be compared with each line of t2, that is to say, t2 needs to be scanned 50000 times from start to end. if the data is bigger, the patient cannot wait, so you have to find a solution. here you can use indexes. I will not talk about the benefits of creating an index here. I just want to talk about how to use an index.
In fact, it is very simple. you don't need to change anything else. you only need to do two more things before querying:
1. create an index for t1;
2. create an index for t2;
The statement for creating an index is:
[sql] create index Num_i1 on t1(Num); create index Num_i2 on t2(Num);
After executing the same query statement, it would take a few minutes to run without an index on my computer. after the index is added, the results will be displayed in the twinkling of an eye.
Therefore, when the data volume is large, you must remember to use indexes. if there are multiple filtering conditions, you can also index multiple columns. For example
create index Num_i1 on t1(ID,Num);
BitsCN.com