繁体   English   中英

嵌套 SQL 查询需要很长时间才能执行

[英]Nestesed SQL query taking to much time to execute

我正在编写一个 SQL 查询来计算该特定日期的用户总数

查询如下:-

select plan_date, type_name, account_type_id, new_type
FROM (
    select
        final_reporting_db.plan_change_facts.date as plan_date,
        final_reporting_db.plan_dim.account_type as type_name,
        final_reporting_db.plan_dim.id as account_type_id,
        (
            select count(*) as new_type from final_reporting_db.plan_change_facts
            where final_reporting_db.plan_change_facts.plan_status_dim_id = account_type_id
            and final_reporting_db.plan_change_facts.date = plan_date
        ) as new_type
    FROM 
        final_reporting_db.plan_change_facts
    INNER JOIN final_reporting_db.plan_dim where final_reporting_db.plan_dim.id in(1,2,3,4,5,6,8,9,13)
) main_table where plan_date between '2016-04-24' and '2016-04-28' group by plan_date, type_name;

在此查询中,子查询执行时间过长,因为它正在计算该日期的计数。

我对如何提高此查询性能感到困惑。 因为执行需要 36 秒。 有没有办法使用 group by 子句而不是使用嵌套查询。 帮助将不胜感激

首先,您的查询几乎无法阅读。 我想出的最好的是:

select cf.date as plan_date,
       d.account_type as type_name, d.id as account_type_id,
       (select count(*) as new_type
        from final_reporting_db.plan_change_facts cf2
        where cf2.plan_status_dim_id = ??.account_type_id and 
              cf2.date = ??.plan_date
-------------------------^ I assume this should be cf
       ) as new_type
from final_reporting_db.plan_change_facts cf join
     final_reporting_db.plan_dim d
-----^ where is the `on` clause ???
where d.id in(1,2,3,4,5,6,8,9,13) and
      cf.date between '2016-04-24' and '2016-04-28'
group by plan_date, type_name;

我观察到以下几点:

  • 子查询中的相关条件什么都不做,因为它们只比较子查询中的列。
  • 您缺少最终连接的on子句,因此这是笛卡尔积。
  • 我怀疑您使用的是实现子查询的 MySQL。 因此,您不希望在group by之前有子查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM