我有以下查询,它给了我正确的结果。但它超级慢。
是什么让它变慢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
答案 0 :(得分:1)
您是否尝试用EXISTS替换IN?
AND EXISTS (SELECT 1 FROM st_address b WHERE a.id = b.id)
EXISTS部分应在找到与条件匹配的第一行后立即停止子查询。我已经阅读了相互矛盾的评论,如果这实际发生了,那么你可能会在那里抛出一个限制1,看看你是否获得任何收益。
答案 1 :(得分: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