我有遗留代码有sql查询,现在我需要优化该查询,因为它在生产服务器中花费的时间太长(14秒)。我仍然不确定从哪里开始。特别是在rand()函数中,因为它似乎有性能问题
SELECT
order_detail.product_id,
dtb_products.name,
dtb_products.main_list_image,
dtb_products_price.price01_min,
dtb_products_price.price01_max,
dtb_products_price.price02_min,
dtb_products_price.price02_max,
dtb_products.limited_flag,
dtb_products.limited_start_date,
dtb_products.limited_end_date
FROM
dtb_order
INNER JOIN
(SELECT
dtb_order_2.customer_id
FROM
dtb_order AS dtb_order_2
INNER JOIN
dtb_order_detail
ON
dtb_order_detail.order_id = dtb_order_2.order_id
WHERE
dtb_order_detail.product_id = 1256
GROUP BY
dtb_order_2.customer_id
) AS CUSTOMER
ON
dtb_order.customer_id = CUSTOMER.customer_id
INNER JOIN
(SELECT
dtb_order_detail.product_id,
dtb_order_detail.order_id
FROM
dtb_order_detail
INNER JOIN
dtb_products
ON
dtb_products.product_id = dtb_order_detail.product_id
WHERE
dtb_order_detail.product_id <> 1256 AND dtb_products.del_flg = 0 AND dtb_products.status = 1
) AS order_detail
ON
order_detail.order_id = dtb_order.order_id
LEFT JOIN
(
SELECT product_id as product_id_sub,
MIN(price01) AS price01_min,
MAX(price01) AS price01_max,
MIN(price02) AS price02_min,
MAX(price02) AS price02_max
FROM dtb_products_class
GROUP BY product_id
) AS dtb_products_price
ON
order_detail.product_id = dtb_products_price.product_id_sub
LEFT JOIN
dtb_products
ON
dtb_products.product_id = order_detail.product_id
GROUP BY
order_detail.product_id
ORDER BY
rand()
limit
8;
我应该从哪里开始优化该查询?
我已经阅读了几篇博文,其中一篇是http://explainextended.com/2009/03/01/selecting-random-rows/,但我仍然在弄清楚如何在上面的查询中实现该方法。
我非常感谢你的帮助。
谢谢
修改
要求是:
获取那些使用固定产品ID购买的产品ID,例如1256 然后从价格表中获取每个产品信息。
修改
查询中的表
dtb_order
,dtb_order_detail
,dtb_products
,dtb_products_class
答案 0 :(得分:-2)
我没有阅读你的问题正文,但像往常一样,我确实限制80,将sql结果集保存到一些缓存存储中(你可以使用json编码,或序列化,并将内容放入文件中),当你需要时,从你的存储中获取它,并从中获取8个随机项。另外,考虑缓存存储重置功能,当您向表中添加一些数据时。