我一直在努力解决这个问题。它耗时超过12秒并且无法弄清楚原因,因为所有三张桌子都有礼服,所以它会慢得多。
SELECT SUM(quantity), rprice, media_file, url, title
FROM inventory, ndxz_objects, ndxz_media
WHERE productid = ndxz_objects.id
AND media_ref_id = ndxz_objects.id
AND productid = media_ref_id
AND media_order = (SELECT MIN(media_order) FROM ndxz_media WHERE media_ref_id = ndxz_objects.id )
GROUP BY productid
ORDER BY productid DESC
Theres是ndxz_objects.id
和productid
答案 0 :(得分:1)
缓慢是由嵌套查询引起的,因为每个media_ref_id = ndxz_objects.id都需要进行表扫描
你需要在ndxz_media表的media_ref_id和media_order上创建一个索引
我还建议使用连接重写查询
答案 1 :(得分:0)
我猜你还需要ndxz_media.media_ref_id
上的索引。 (我也猜测那是media_ref_id
列的来源,因为你没有非常清楚地列出列名。)
相同的索引应该包含media_order作为第二列。
答案 2 :(得分:0)
问题几乎可以肯定是相关子查询,每行执行一次,即使索引此类查询也不是很好。我认为以下应该会达到相同的效果。
SELECT SUM(quantity), rprice, media_file, url, title
FROM inventory, ndxz_objects, ndxz_media,
(SELECT MIN(media_order) as order FROM ndxz_media GROUP BY media_ref_id) min_orders
WHERE productid = ndxz_objects.id
AND media_ref_id = ndxz_objects.id
AND productid = media_ref_id
AND media_order = min_orders.order
GROUP BY productid
ORDER BY productid DESC
虽然您提供的查询实际上无效,因为rprice, media_file, url, title
未汇总或在group by子句中