简体   繁体   中英

optimizing query (LEFT JOIN)

My goal is to show search results of companies both: with categories and without (not added yet). My companies table has more or less 12 000 records. Companies with categories are only more or less 200.

There are two search inputs: $name -> name of company or category. $id_country -> id of the country

I want to display: 1) how many results is in all database. (that's why i use: SQL_CALC_FOUND_ROWS) 2) i use LIMIT to show 10 results per page (with pagination).

My query:

SELECT SQL_CALC_FOUND_ROWS 
c.*, 
lc.name as langName,
lc.shortDesc,
lc.longDesc 

FROM companies c 
JOIN lang_companies lc USING(id_company) 
LEFT JOIN categories_companies cc USING(id_company)
LEFT JOIN lang_categories lang_cat USING (id_category) 

WHERE 
lc.id_lang = '2' AND c.status = 1 AND c.active = 1 AND  c.id_country = ".$id_country." AND 
(lc.name = LCASE('".$name."') OR (lang_cat.name = LCASE('".$name."') AND lang_cat.id_lang = '2')
OR c.city = '".$name."')
GROUP BY c.id_company 
ORDER BY c.id_hierarchi asc 
LIMIT 0, 10

This query executes more or less 6 seconds and I want to optimize it. Could you help me? I will be grateful for any suggestions.

Out of the FROM part of your query, you do not seem to actually use the tables which are joined with these two lines:

LEFT JOIN categories_companies cc USING(id_company)
LEFT JOIN categories cat USING (id_category) 

I presume you can simply exclude them from the query, if they are not relevant through something more sublte like the join suppressing rows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM