需要优化以下MySQL查询

时间:2013-11-14 12:27:52

标签: mysql select distinct

我已成功尝试此查询并设置了限制。以下查询无限制地运行:

SELECT o.product_sku
FROM   order_table o
WHERE  EXISTS (SELECT 1
           FROM   (SELECT DISTINCT u.type_id,
                                   u.charge_type,
                                   u.billed_weight
                   FROM   ups_table u
                   WHERE  charge_type = 'order_shipping_table'
                          AND NOT billed_weight = '0'
                   ) dtm
           WHERE  o.order_id = dtm.type_id)
GROUP  BY product_sku
HAVING Count(product_sku) > 1

1 个答案:

答案 0 :(得分:0)

首先,您不需要使用DISTINCT的这些子查询,依此类推:

SELECT o.product_sku
FROM   order_table o
WHERE  EXISTS (SELECT 1
                   FROM   ups_table u
                   WHERE  charge_type = 'order_shipping_table'
                          AND NOT billed_weight = '0'
                          AND type_id=o.order_id
               )
GROUP  BY product_sku
HAVING Count(product_sku) > 1

我不知道你的表结构(你想在HAVING中算什么?)但你可以尝试将EXISTS改为JOIN:

SELECT o.product_sku
FROM   order_table o
JOIN ups_table u on (u.type_id=o.order_id)
                    AND (u.charge_type = 'order_shipping_table')
                    AND NOT (billed_weight = '0')
GROUP  BY product_sku
HAVING Count(DISTINCT o.order_id) > 1

您需要o.order_id, o.product_sku, u.type_id,u.charge_type, u.billed_weight

上的索引