我在使用以下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;是否可以在没有子查询的情况下获得订单数,或者获得正确的订单数?求求你帮帮我。谢谢!
发布于 2019-02-14 12:40:26
LEFT JOIN,它告诉你,即使在‘’表中没有行,也要继续查找。但是,从另一方面来说,您正在对LEFT JOINs链的最后一列执行GROUPing BY操作!也许你的意思是JOIN而不是LEFT JOIN??LEFT JOINs大致等同于说"Oops,所有那些可能是LEFT JOIN??GROUP BY和JOINs (LEFT或其他),你正在做“膨胀-收缩”。从逻辑上讲,JOINing所做的全部工作就是构建一个包含所有有效组合的巨大中间表。然后COUNT(*)和GROUP BY就完成了。这往往会使COUNTs (和SUMs等)具有比expected.department到order的最直接途径?它似乎不涉及store,因此删除该表。即使在解决了这些问题之后,您仍然可能得到错误的值。对于初学者,请为每个表提供‘`SHOW CREATE table’。
https://stackoverflow.com/questions/54663038
复制相似问题