在大数据量的SQL表中,往往会出现一些查询效率低的问题,耗时,如果解决这里问题呢?本文主要探索索引在提高SQL效率的有效性。
目录
1、创建数据表
2、为建立索引之前,查看执行效率
3、给Name建立索引
4、查看索引
1、创建数据表
我让chatgpt帮我创建了一张一万条数据的表,你们可以创建的多一点,效果更明显
CREATE TABLE BigDataTable (
ID INT PRIMARY KEY,
Name VARCHAR(100),
Description TEXT,
CreatedDate DATE,
Value DECIMAL(10, 2)
);
-- 插入大约一万行数据
INSERT INTO BigDataTable (ID, Name, Description, CreatedDate, Value)
SELECT
n,
CONCAT('Name', n),
CONCAT('Description for entry ', n),
DATE_ADD('2020-01-01', INTERVAL n DAY),
RAND() * 1000
FROM
(SELECT t0.n + t1.n * 10 + t2.n * 100 + t3.n * 1000 AS n
FROM
(SELECT 0 AS n UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS t0,
(SELECT 0 AS n UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS t1,
(SELECT 0 AS n UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS t2,
(SELECT 0 AS n UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS t3) AS numbers
WHERE n < 10000;
2、为建立索引之前,查看执行效率
select * from BigDataTable where id=1;
select * from BigDataTable where Name='Name10';
我们会看到检索id比检索Name更快(如果数据量更大的话,效率差距会更明显的),这里的原因是,在创建表的时候id是主键,主键直接就是创建了索引,也就是主键索引。所以比Name快。那么如何提升查询速度呢?我们可以给Name字段建立索引。
3、给Name建立索引
create index index_Name on BigDataTable(Name);
当我们再一次使用查询语句的时候会发现使用时间变短了,由此也验证了索引的效率
4、查看索引
explain select * from BigDataTable where Name='Name1' and id=1;
发现Name和id都是索引,表里面的字段含义可以看上一篇文章Explain字段含义