简体   繁体   中英

Nestesed SQL query taking to much time to execute

I am writing an SQL query to calculate the total number of users at that particular date

query is below :-

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;

In this query sub query taking too much time to execute because it is calculating the count for that date.

i am confused about how to improve this query performance. as it taking 36 sec to execute. is there any way to use group by clause instead of using nested query. Help will appreciated

First, your query is almost impossible to read. The best that I've come up with is:

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;

I observe the following:

  • The correlation conditions in the subquery are doing nothing, because they are comparing only columns in the subquery.
  • You are missing an on clause for the final join, so this is a Cartesian product.
  • I suspect you are using MySQL, which materializes subqueries. So, you don't want a subquery before the group by .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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