-- 创建大数据量测试表CREATETABLE performance_test (
id INTPRIMARYKEYAUTO_INCREMENT,
username VARCHAR(50),
email VARCHAR(100),
age INT,
city VARCHAR(50),
registration_date DATE);-- 插入大量测试数据DELIMITER//CREATEPROCEDURE insert_test_data()BEGINDECLARE i INTDEFAULT0;WHILE i <1000000DOINSERTINTO performance_test
(username, email, age, city, registration_date)VALUES(
CONCAT('user_', i),
CONCAT('user_', i,'@example.com'),
FLOOR(RAND()*50+18),CASE FLOOR(RAND()*5)WHEN0THEN'北京'WHEN1THEN'上海'WHEN2THEN'广州'WHEN3THEN'深圳'ELSE'杭州'END,
DATE_SUB(CURRENT_DATE,INTERVAL FLOOR(RAND()*3650)DAY));SET i = i +1;ENDWHILE;END//DELIMITER;-- 调用存储过程插入数据CALL insert_test_data();
5.1.2 不同类型索引
-- 普通索引CREATEINDEX idx_username ON performance_test(username);-- 唯一索引CREATEUNIQUEINDEX idx_email ON performance_test(email);-- 复合索引CREATEINDEX idx_age_city ON performance_test(age, city);-- 全文索引(需要FULLTEXT引擎)CREATE FULLTEXT INDEX idx_fulltext_username ON performance_test(username);
5.2 性能分析实践
5.2.1 EXPLAIN分析查询
-- 未优化查询EXPLAINSELECT*FROM performance_test
WHERE username ='user_500000';-- 使用索引后的查询EXPLAINSELECT*FROM performance_test
WHERE username ='user_500000';
5.2.2 慢查询日志分析
-- 配置慢查询日志(需要在MySQL配置文件中设置)SETGLOBAL slow_query_log ='ON';SETGLOBAL long_query_time =1;-- 记录超过1秒的查询-- 模拟慢查询SELECT*FROM performance_test
WHERE age >30ORDERBY registration_date
LIMIT10000;
5.3 查询优化技巧
5.3.1 索引优化
-- 不走索引的查询EXPLAINSELECT*FROM performance_test
WHEREYEAR(registration_date)=2022;-- 优化后的查询CREATEINDEX idx_registration_date ON performance_test(registration_date);-- 避免在索引列使用函数EXPLAINSELECT*FROM performance_test
WHERE registration_date >='2022-01-01';
5.3.2 JOIN优化
-- 创建关联表CREATETABLE user_orders (
order_id INTPRIMARYKEYAUTO_INCREMENT,
user_id INT,
order_amount DECIMAL(10,2),
order_date DATE);-- 插入测试数据INSERTINTO user_orders (user_id, order_amount, order_date)SELECT
id,ROUND(RAND()*1000,2),
DATE_SUB(CURRENT_DATE,INTERVAL FLOOR(RAND()*365)DAY)FROM performance_test
LIMIT100000;-- 未优化的连接查询EXPLAINSELECT
pt.username,
uo.order_amount
FROM performance_test pt
JOIN user_orders uo ON pt.id = uo.user_id
WHERE pt.age >30;-- 添加索引优化CREATEINDEX idx_user_id ON user_orders(user_id);CREATEINDEX idx_age ON performance_test(age);
5.3.3 分页优化
-- 传统分页(性能较差)EXPLAINSELECT*FROM performance_test
ORDERBY id
LIMIT100000,20;-- 优化的分页查询EXPLAINSELECT*FROM performance_test
WHERE id >(SELECT id FROM performance_test
ORDERBY id
LIMIT100000,1)ORDERBY id
LIMIT20;