H
H
Herman Martin2018-05-18 18:25:35
MySQL
Herman Martin, 2018-05-18 18:25:35

How to optimize a query?

There is a request:

select ( select SUM(e.summ)
        from myevents.event as e
          LEFT JOIN myevents.type as t on t.id = e.type
        WHERE (e.dtr >= '2018-04-01') AND (e.dtr <= '2018-04-31') AND
              (t.id = 1))  as 'dohod',
        (select SUM(e.summ)
        from myevents.event as e
          LEFT JOIN myevents.type as t on t.id = e.type
        WHERE (e.dtr >= '2018-04-01') AND (e.dtr <= '2018-04-31') AND
              (t.id = 2)) as 'rashod';

select ( select SUM(e.summ)
         from myevents.event as e
           LEFT JOIN myevents.type as t on t.id = e.type
         WHERE (e.dtr >= '2018-05-01') AND (e.dtr <= '2018-05-31') AND
               (t.id = 1))  as 'dohod',
       (select SUM(e.summ)
        from myevents.event as e
          LEFT JOIN myevents.type as t on t.id = e.type
        WHERE (e.dtr >= '2018-05-01') AND (e.dtr <= '2018-05-31') AND
              (t.id = 2)) as 'rashod';

It finds the amount of income and expenses for 1 month, or rather the first query finds it. The second query does the same, but for the next month. Interested in ways to optimize such a query. Most likely there are ways where you can get the same data for several months with 1 request. Need some guidance
And is there any way to get rid of nested queries to get the same thing?
Any directions to good links and/or books (or other) for studying similar issues are welcome.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Entelis, 2018-05-18
@dklight

how it is downright sad.
1. You join the type table by id and immediately filter by it - filter immediately by event.type, the type table is not needed at all
2. If you need it in a few months, then in terms of performance, the fastest solution is sampling

select DATE_FORMAT(event .dtr,"%Y-%m"), event.type, sum(event.summ),
from event 
where event  dtr between ... and ...
group by DATE_FORMAT(event .dtr,"%Y-%m"), event.type, sum(event.summ)

and further on any PL to process it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question