mysql用存储过程插入百万条数据, 及查询优化

查看所有存储过程:

show procedure status;  

查看详细存储过程 ptest:

show create procedure ptest;  

  

存储过程插入数据:

create table milli(id int auto_increment primary key, name varchar(20), num int);
truncate table milli;
delimiter $$
drop procedure if exists ptest;
create procedure ptest()
begin
declare pid int ;
set pid = 100000;
while pid>0 do
insert into milli values(null, "lili");
set pid = pid-1;
end while;
end $$
call ptest();

 

mysql查询优化:

那么如果我们也要查询所有列,有两种方法,一种是id>=的形式,另一种就是利用join,看下实际情况:

SELECT * FROM product WHERE ID > =(select id from product limit 866613, 1) limit 20
查询时间为0.2秒,简直是一个质的飞跃啊,哈哈

另一种写法
SELECT * FROM product a JOIN (select id from product limit 866613, 20) b ON a.ID = b.id
查询时间也很短,赞!

总结:

1.mysql嵌套子查询效率确实比较低

2.可以将其优化成连接查询

3.连接表时,可以先用where条件对表进行过滤,然后做表连接

(虽然mysql会对连表语句做优化)

4.建立合适的索引,必要时建立多列联合索引

5.学会分析sql执行计划,mysql会对sql进行优化,所以分析执行计划很重要

SELECT s.* from Student s INNER JOIN SC sc on sc.s_id = s.s_id where sc.c_id=0 and sc.score=100

  

 

原文地址:https://www.cnblogs.com/wujixing/p/5434923.html