优化sql多个左连接和where子句

时间:2014-07-21 06:46:37

标签: mysql sql

SELECT distinct text FROM oc_product_attribute as pa
LEFT JOIN oc_product_to_category as ptc ON  pa.product_id = ptc.product_id
LEFT JOIN oc_product as p ON pa.product_id = ptc.product_id
WHERE p.status = 1 AND ptc.category_id = 61 
GROUP BY pa.text LIMIT 10

虽然我使用LIMIT,但我的数据库挂起以进行上述查询。有什么方法可以优化它吗?

2 个答案:

答案 0 :(得分:0)

在此行中,您应使用别名p而不是ptc

LEFT JOIN oc_product as p ON pa.product_id = ptc.product_id

应该是

LEFT JOIN oc_product as p ON pa.product_id = p.product_id

答案 1 :(得分:0)

我认为此查询中不需要DISTINCTGROUP BY,因为您无论如何都要使用where子句中的两个表。另外,因为您只是选择文本列。您可以考虑将查询重写为:

SELECT 
    pa.text 
FROM 
    oc_product_attribute as pa
WHERE EXISTS
(
    SELECT
        NULL
    FROM
        oc_product_to_category as ptc 
        JOIN oc_product as p 
            ON p.product_id = ptc.product_id
    WHERE  
        pa.product_id = ptc.product_id
        AND p.status = 1 
        AND ptc.category_id = 61
)
LIMIT 10