1

我有以下查询,它给了我正确的结果。但是超级慢。让它变慢的是

AND a.id IN (SELECT id FROM st_address GROUP BY element_id)

部分。查询应该显示我们从哪些国家获得了多少订单。
一个人可以有多个地址,但在这种情况下,我们只想要一个。
否则它将多次计算订单。也许有更好的方法来实现这一目标?一个人或某事的独特连接?

SELECT cou.title_en, COUNT(co.id), SUM(co.price) AS amount
FROM customer_order co
JOIN st_person p ON (co.person_id = p.id)
JOIN st_address a ON (co.person_id = a.element_id AND a.element_type_id = 1)
JOIN st_country cou ON (a.country_id = cou.id) 
WHERE order_status_id != 7 AND a.id IN (SELECT id FROM st_address GROUP BY element_id)
GROUP BY cou.id 
4

2 回答 2

1

您是否尝试将 IN 替换为 EXISTS?

AND EXISTS (SELECT 1 FROM st_address b WHERE a.id = b.id)

一旦找到与条件匹配的第一行,EXISTS 部分就应该停止子查询。我已经阅读了关于这是否真的发生的相互矛盾的评论,因此您可能会在其中设置限制 1 以查看是否有任何收益。

于 2012-04-10T13:18:46.910 回答
0

我找到了一个更快的解决方案。诀窍是与子查询连接:

JOIN (SELECT element_id, country_id, id FROM st_address WHERE element_type_id = 1 GROUP BY 

这是完整的查询:

SELECT cou.title_en, COUNT(o.id), SUM(o.price) AS amount 
FROM customer_order o
JOIN (SELECT element_id, country_id, id FROM st_address WHERE element_type_id = 1 GROUP BY element_id) AS a ON (o.person_id = a.element_id)
JOIN st_country cou ON (a.country_id = cou.id) 
WHERE o.order_status_id != 7 
GROUP BY cou.id 
于 2012-04-11T08:27:48.213 回答