寻求一些帮助来优化下面的查询。目前似乎有两个瓶颈导致它需要大约 90 秒才能完成查询。只有 5000 种产品,因此它并不是一个庞大的数据库/表。瓶颈是 SQL_CALC_FOUND_ROWS 和 ORDER BY 语句——如果我删除这两个语句,运行查询大约需要一秒钟。 我试过删除 SQL_CALC_FOUND_ROWS 并运行 count() 语句,但这也需要很长时间..
根据以下 Stackoverflow 帖子,最好的办法是使用 INNER JOIN(我不太熟悉)吗? 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
最佳答案
您可以尝试通过使用派生表在连接之前检索过滤和排序的产品来减少连接的大小。这假设 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
)
这是“暗中刺杀”,因为您的问题中没有足够的细节。
关于MySQL 查询优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9897685/