Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

多表联合查询优化

explain select SQL_CALC_FOUND_ROWS * from task a,user b ,task_project c,task_platform d where a.user_id = b.id and a.project_id = c.id and c.platform_id = d.id order by a.time_created desc limit 10 offset 0;
image

这条语句查询要3s,如果分开来查时间加起来不超过1s,
问题好像出在 c.platform_id = d.id 与a表无关联。
求优化。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. 表task建立time_created索引
  2. 统计条数和分页分开计算,不使用SQL_CALC_FOUND_ROWS
  3. 不使用select *,只取需要的字段

个人建议:SQL不要使用where形式的笛卡尔积连接,而是指明left join或者是inner join,这样更直观,效率貌似也比较高。
按照表名简单推断应该是要查出最近创建的10个task,改造成left join:

select *
from task a
 left join `user` b on a.user_id = b.id
 left join task_project c on a.project_id = c.id
 left join task_platform d on c.platform_id = d.id
order by a.time_created desc 
limit 10 offset 0;

如果要求a.user_id要关联到b.id,那要改成inner join。
如果没有where条件,完全可以改成如下,查询效率应该是毫秒级:

select *
from (select * from task order by time_created desc limit 10 offset 0)a
 left join `user` b on a.user_id = b.id
 left join task_project c on a.project_id = c.id
 left join task_platform d on c.platform_id = d.id
order by a.time_created desc;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...