使用rand()使用各种连接和顺序优化mysql查询

时间:2018-03-02 19:40:54

标签: mysql database join random explain

我的网站出现问题,所以我查看了mysql慢查询日志。

修复了一些索引,并且在没有连接的情况下查询,现在服务器负载降低,运行正常。

我仍然有一个我无法解决的问题,如果你们有任何提示,我可以做得更好,我会很感激。

这是查询

SELECT p.product_id,
          p.product_offer_price,
          ps.subcategory_name,
          pb.brand_name,
          pm.model_name,
          pm.display_name,
          pm.year_from,
          pm.year_to 
        FROM product p
        INNER JOIN product_subcategory ps ON ps.subcategory_id = p.product_subcategory_id AND ps.subcategory_category_id = 12
        INNER JOIN product_stock pq ON pq.product_id = p.product_id AND pq.product_quantity > 0
        INNER JOIN product_photos pp ON pp.product_id = p.product_id
        INNER JOIN product_brand pb ON pb.brand_id = p.product_brand_id
        INNER JOIN product_model pm ON pm.model_id = p.product_model_id
        GROUP BY p.product_id
        ORDER BY RAND() LIMIT 4;

这是关于查询的解释 https://imgur.com/a/LpIJe

我试图完成这样的事情,但是没有工作

SELECT p.product_id, p.product_offer_price, ps.subcategory_name, pb.brand_name, pm.model_name, pm.display_name, pm.year_from, pm.year_to
FROM product p
INNER JOIN product_subcategory ps ON ps.subcategory_id = p.product_subcategory_id
AND ps.subcategory_category_id =12
INNER JOIN product_stock pq ON pq.product_id = p.product_id
AND pq.product_quantity >0
INNER JOIN product_photos pp ON pp.product_id = p.product_id
INNER JOIN product_brand pb ON pb.brand_id = p.product_brand_id
INNER JOIN product_model pm ON pm.model_id = p.product_model_id
WHERE p.product_id >= FLOOR( 1 + RAND( ) * (
SELECT MAX( product_id )
FROM product ) )
GROUP BY p.product_id
LIMIT 4

0 个答案:

没有答案