2012-03-27 44 views
2

寻找一些帮助优化下面的查询。似乎是目前的两个瓶颈,导致它需要大约90秒才能完成查询。只有5000个产品,因此它不是一个庞大的数据库/表格。瓶颈是SQL_CALC_FOUND_ROWS和ORDER BY语句 - 如果我删除这两者,则需要大约一秒的时间才能运行查询。 我试过删除SQL_CALC_FOUND_ROWS并运行一个count()语句,但这需要很长时间。MySQL查询优化

是最好的事情将是使用INNER JOIN的(我不太熟悉)根据以下Stackoverflow的帖子? Slow query when using ORDER BY

SELECT SQL_CALC_FOUND_ROWS * 
FROM tbl_products 
LEFT JOIN tbl_link_products_categories ON lpc_p_id = p_id 
LEFT JOIN tbl_link_products_brands ON lpb_p_id = p_id 
LEFT JOIN tbl_link_products_authors ON lpa_p_id = p_id 
LEFT JOIN tbl_link_products_narrators ON lpn_p_id = p_id 
LEFT JOIN tbl_linkfiles ON lf_id = p_id 
AND (
lf_table = 'tbl_products' 
OR lf_table IS NULL 
) 
LEFT JOIN tbl_files ON lf_file_id = file_id 
AND (
file_nameid = 'p_main_image_' 
OR file_nameid IS NULL 
) 
WHERE p_live = 'y' 
ORDER BY p_title_clean ASC, p_title ASC 
LIMIT 0 , 10 
+1

您是否需要将所有这些连接都留给连接?你是否理解内连接和左连接的区别? – nnichols 2012-03-27 21:14:12

+0

你能告诉我们一些CREATE TABLE语句吗?你有什么指数? – Daan 2012-03-27 21:26:22

+0

产品不一定需要类别,品牌,作者,解说员或任何链接文件..据我所知,在这种情况下,我需要使用LEFT JOIN。因为如果我使用INNER JOINS,它不会匹配某些项目上的任何内容? – 2012-03-27 21:28:24

回答

1

你可以尝试缩小尺寸的使用派生表检索过滤和排序后的产品加入之前加入。这假定p_live,p_title_clean和p_title在你tbl_products表中的字段 -

SELECT * 
FROM (SELECT * 
    FROM tbl_products 
    WHERE p_live = 'y' 
    ORDER BY p_title_clean ASC, p_title ASC 
    LIMIT 0 , 10 
) AS tbl_products 
LEFT JOIN tbl_link_products_categories 
    ON lpc_p_id = p_id 
LEFT JOIN tbl_link_products_brands 
    ON lpb_p_id = p_id 
LEFT JOIN tbl_link_products_authors 
    ON lpa_p_id = p_id 
LEFT JOIN tbl_link_products_narrators 
    ON lpn_p_id = p_id 
LEFT JOIN tbl_linkfiles 
    ON lf_id = p_id 
    AND (
     lf_table = 'tbl_products' 
     OR lf_table IS NULL 
    ) 
LEFT JOIN tbl_files 
    ON lf_file_id = file_id 
    AND (
     file_nameid = 'p_main_image_' 
     OR file_nameid IS NULL 
    ) 

这是因为没有足够的细节在你的问题是“在黑暗中刺”。

+0

感谢此 - 不得不略微调整它,但这有助于我理解如何正确优化它。 – 2012-04-01 21:03:54