优化长时间运行的SELECT DISTINCT查询以及在查询中使用“EXPLAIN”的位置?

时间:2012-09-11 01:57:25

标签: php mysql

我在下面的代码中确切使用EXPLAIN,并且任何人都可以建议如何加速/优化此代码(对于jobseeker表中的4百万行jos_users表)

$query =  " SELECT DISTINCT a.*,b.name,dl.id id_deg,dl.degree_level,
               (SELECT r.hits FROM #__jbjobs_resume_view r WHERE r.jseeker_id=a.user_id AND r.employer_id=$user->id) AS hits, 
               (SELECT featured FROM #__jbjobs_resume WHERE is_active='y' AND featured=1 AND featured_expire > NOW() AND jseeker_id=a.user_id) as featuredres FROM #__jbjobs_jobseeker a".
              " LEFT JOIN #__users b ON a.user_id=b.id ".
              " LEFT JOIN #__jbjobs_degree_level dl ON a.id_degree_level = dl.id".
              " LEFT JOIN #__jbjobs_custom_field_value c ON c.userid=a.user_id".
              " WHERE ".$where."AND b.block='0'".
              " ORDER BY featuredres DESC";

Structure 1 struc2 struct3

1 个答案:

答案 0 :(得分:2)

resume_view.hits和resume.featured只返回0或1行?如果是这样,您应该能够通过LEFT JOIN完成所有操作。如果有零行,则该值将为NULL。

SELECT DISTINCT a.*,b.name,dl.id id_deg,dl.degree_level, 
      r.hits,  
      r2.featured AS featuredres
 FROM #__jbjobs_jobseeker a 
    LEFT JOIN #__users b ON a.user_id=b.id  
    LEFT JOIN #__jbjobs_degree_level dl ON a.id_degree_level = dl.id 
    LEFT JOIN #__jbjobs_custom_field_value c ON c.userid=a.user_id 

    LEFT JOIN #__jbjobs_resume_view r ON r.jseeker_id=a.user_id AND r.employer_id = $user_id
    LEFT JOIN #__jbjobs_resume r2 ON r2.is_active='y' AND r2.featured=1 AND r2.featured_expire > NOW() AND r2.jseeker_id=a.user_id

    WHERE $where AND b.block='0' 
    ORDER BY featuredres DESC