如何获取订单计数子查询

时间:2019-02-13 05:19:50

标签: mysql mariadb

我很难通过以下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;

是否可以在不进行子查询的情况下获得订单计数或获得正确的订单数量?请帮忙...谢谢!

1 个答案:

答案 0 :(得分:0)

  • 您有scipy.interpolate,它表示即使“正确”的表中没有行,也可以继续查找。但是,另一方面,您是LEFT JOIN链中最后一个的GROUPing BY列!也许您是说LEFT JOINs而不是JOIN ??

  • LEFT JOIN大致等于说“糟糕,所有这些where d.id is not null都可能是LEFT JOINs

  • 使用JOINsGROUP BY(或其他JOINs),您正在执行“ inflate-deflate”。逻辑上发生的是,所有LEFT都已完成,以构建具有所有有效组合的巨大中间表。 然后完成JOINingCOUNT(*)。这往往会使GROUP BY(和COUNTs等)的值大于预期。

  • SUMsdepartment的最直接路线是什么?它似乎不涉及order,因此请删除该表。

  • 其他表格是否不相关?

即使解决了这些问题,您仍然可能会得到错误的值。首先,请为每个表提供“ SHOW CREATE TABLE”。