我很难通过以下SQL查询获得订单计数:
select
d.id,
d.title,
count(distinct o.id)
from store s
left join `order` o on o.store_id = s.id
left join order_product op on op.order_id=o.id
left join store_product sp on sp.id = op.product_id
left join product p on p.id = sp.product_id
left join department_category_to_entity dce1 on dce1.entity_type IN ('Product') and dce1.entity_id = p.id
left join department_category_to_entity dce2 on op.status != 'replaced' and
op.replacement_id is null and
dce2.entity_type IN ('StoreProduct') and
dce2.entity_id = sp.id
left join department_category_to_entity dce3 on op.status = 'replaced' and
op.replacement_id is not null and
dce3.entity_type IN ('StoreProduct') and
dce3.entity_id = op.replacement_id
left join department_category dc on dc.id = p.department_category_id or
dc.id = dce1.category_id or
dc.id = dce2.category_id or
dc.id = dce3.category_id
left join department d on d.id = dc.department_id
where d.id is not null
group by d.id;
是否可以在不进行子查询的情况下获得订单计数或获得正确的订单数量?请帮忙...谢谢!
答案 0 :(得分:0)
您有scipy.interpolate
,它表示即使“正确”的表中没有行,也可以继续查找。但是,另一方面,您是LEFT JOIN
链中最后一个的GROUPing BY
列!也许您是说LEFT JOINs
而不是JOIN
??
说LEFT JOIN
大致等于说“糟糕,所有这些where d.id is not null
都可能是LEFT JOINs
。
使用JOINs
和GROUP BY
(或其他JOINs
),您正在执行“ inflate-deflate”。逻辑上发生的是,所有LEFT
都已完成,以构建具有所有有效组合的巨大中间表。 然后完成JOINing
和COUNT(*)
。这往往会使GROUP BY
(和COUNTs
等)的值大于预期。
从SUMs
到department
的最直接路线是什么?它似乎不涉及order
,因此请删除该表。
其他表格是否不相关?
即使解决了这些问题,您仍然可能会得到错误的值。首先,请为每个表提供“ SHOW CREATE TABLE”。