在查询中花费太长时间

时间:2014-04-25 08:08:15

标签: mysql

我有一个带有IN子句的查询,处理时间太长,不知道出了什么问题:

 Select * from orders
 where orders.id IN 
(
    SELECT orders.id FROM `orders` 
    INNER JOIN `line_items` ON `line_items`.`order_id` = `orders`.`id` 
    WHERE (line_items.coupon_id = 133) 
    GROUP BY orders.id 
    UNION 
    SELECT orders.id FROM `orders` 
    INNER JOIN `payments` ON `payments`.`order_id` = `orders`.`id`
    WHERE (payments.coupon_id = 133) 
    GROUP BY orders.id 
    UNION 
    SELECT orders.id FROM `orders` 
    INNER JOIN `coupon_applications` ON `coupon_applications`.`order_id` = `orders`.`id` 
    WHERE (coupon_applications.coupon_id =133) 
    GROUP BY orders.id
);

但是以下部分工作正常:

SELECT orders.id FROM `orders` 
INNER JOIN `line_items` ON `line_items`.`order_id` = `orders`.`id` 
WHERE (line_items.coupon_id = 133) 
GROUP BY orders.id 
UNION 
SELECT orders.id FROM `orders` 
INNER JOIN `payments` ON `payments`.`order_id` = `orders`.`id` 
WHERE (payments.coupon_id = 133) 
GROUP BY orders.id 
UNION 
SELECT orders.id FROM `orders` 
INNER JOIN `coupon_applications` ON `coupon_applications`.`order_id` = `orders`.`id`
WHERE (coupon_applications.coupon_id =133) 
GROUP BY orders.id

3 个答案:

答案 0 :(得分:0)

需要多长时间?

优化查询执行有很多限制。您的查询似乎没有问题,除了#34; SELECT *",您最好更改(但这不会大大影响您的查询性能)。

如果您认为查询不正确,请提供有关此问题的更多详细信息。

答案 1 :(得分:0)

首先:避免使用IN()进行子选择,它似乎打破了优化器(编辑:例如,见https://dba.stackexchange.com/a/63671/24475)。只是做

SELECT o.* 
FROM orders as o
inner join...
UNION
SELECT o.*
FROM orders as o
UNION
...

如果某个订单的某个表中有很多行,那么WHERE EXISTS可能会有所帮助(或者根本没有帮助):

 SELECT o.* 
 FROM orders o
 WHERE EXISTS 
 (
     select id from lineitem li where li.coupon_id = 133 and li.order_id = o.id)
 )
 OR EXISTS
 (
     select id from payments where...
 )

答案 2 :(得分:0)

从我的嵌套查询中删除'GROUP BY orders.id'后,我已成功运行它。但无法找到它在嵌套查询中不适用于Group By的原因。

希望这会对其他人有所帮助。

谢谢!