使用多个JOIN和OR运算符进行SQL优化

时间:2017-07-07 20:40:34

标签: sql optimization

我有一个查询,我正在寻找最佳的查询优化方法。这是我生成的查询。是否有更好的方法来优化它以减少内存,CPU使用并使其更快?

SELECT DISTINCT a.*,country,c.id 
id_employer,c.comp_name,c.show_comp_name,comp_type,b.id countryid,if(now()
<a.hotjob_expire, true, false) is_hot 
FROM j5xap_jbjobs_job a 
LEFT JOIN j5xap_jbjobs_country b ON a.id_country = b.id 
LEFT JOIN j5xap_jbjobs_employer c ON a.employer_id = c.user_id 
LEFT JOIN j5xap_jbjobs_custom_field_value cv ON cv.jobid=a.id 
LEFT JOIN j5xap_jbjobs_comp_type d ON c.id_comp_type = d.id 
WHERE (
          a.job_title LIKE '%Web developer%' 
       OR a.state LIKE '%Web developer%' 
       OR a.city LIKE '%Web developer%' 
       OR b.country LIKE '%Web developer%' 
       OR c.comp_name LIKE '%Web developer%' 
       OR cv.value LIKE '%Web developer%' 
       OR cv.valuetext LIKE '%Web developer%' 
       OR a.short_desc LIKE '%Web developer%' 
       OR a.long_desc LIKE '%Web developer%'
      ) 
   OR (
          a.job_title LIKE '%kannur%' 
       OR a.state LIKE '%kannur%'
       OR a.city LIKE '%kannur%' 
       OR b.country LIKE '%kannur%' 
       OR c.comp_name LIKE '%kannur%' 
       OR cv.value LIKE '%kannur%' 
       OR cv.valuetext LIKE '%kannur%' 
       OR a.short_desc LIKE '%kannur%' 
       OR a.long_desc LIKE '%kannur%'
    ) 
    AND a.id_job_spec =441 
    AND a.id_job_spec IN (SELECT id FROM j5xap_jbjobs_job_spec WHERE id_category='63') 
    AND a.is_active='y' 
    AND a.publish_date <= '2017-07-07 00:00:00' 
    AND expire_date  >= '2017-07-07 00:00:00' 
    AND expire_date <> '0000-00-00 00:00:00' 
 ORDER BY is_hot DESC, a.is_featured DESC, a.publish_date DESC, a.id DESC
 LIMIT 0, 10;

我最初的想法是多个连接应该分成单个select语句,但是使用这些多个OR运算符。这有点棘手。

非常感谢任何协助。

谢谢!

1 个答案:

答案 0 :(得分:0)

OR效率低下。

LIKE '%...'效率低下。

IN ( SELECT ... ) 可能效率低下。更改为EXISTS(...)JOIN

正确使用MySQL FULLTEXT索引(并修改查询以使用它)将大大加快查询速度。

expire_date中有哪个表格?

此复合索引可能帮助:

INDEX(id_job_spec, is_active, publish_date)