使用内部联接从多个表进行查询需要很长时间才能执行

时间:2014-07-03 06:54:36

标签: join count

I have an sql query below that is taking too long to execute. kindly check the query and optimise it for me, i need to count number of files from a file_Actions table but combining it three other tables using inner join

SELECT count(*) as total 
FROM (SELECT t1.cfid as cfid,MAX(t1.timestamp) d 
FROM file_actions t1 
INNER JOIN case_files t2 ON t2.cfid=t1.cfid 
INNER JOIN case_file_allocations t3 ON t1.cfid=t3.cfid
INNER JOIN cbeta_user t4 
WHERE t4.id=t1.user_id 
AND t4.team_leader='$user' and t2.closed<>'yes' AND
t2.deleted<>1 AND
t3.reallocated<>'yes' GROUP BY t1.cfid) a 
WHERE d < '$yesterday'

我认为是内部联接导致查询执行时间过长导致系统运行缓慢

1 个答案:

答案 0 :(得分:0)

尝试将WHERE d < '$yesterday'包含在子查询a中。删除字段并放置计数(*)。如果您的表格没有用于条件和关系的那些值,请尝试制作索引。

SELECT count(*) as total
  FROM file_actions t1 
  INNER JOIN case_files t2 
               ON t2.cfid=t1.cfid 
  INNER JOIN case_file_allocations t3 
               ON t1.cfid=t3.cfid
  INNER JOIN cbeta_user t4 
WHERE t4.id=t1.user_id 
 AND t4.team_leader='$user' and t2.closed<>'yes' 
 AND t2.deleted<>1 
 AND t3.reallocated<>'yes' 
 AND d < '$yesterday'
GROUP BY t1.cfid

推荐阅读:http://www.code-fly.com/5-tips-to-make-your-sql-queries-faster/