SELECT count(*) #первый запрос, который бесполезно #выбирает данные из своих подзапросов FROM ( #второй запрос, выбирает ВСЕ даннные без лимитов и ограничений select * from table1 union all #третий запрос, выбирает ВСЕ даннные без лимитов и ограничений select * from table2 ) a #почему вы не ограничили time в подзапросах? WHERE time > 1468443612608 AND time <= 1468530021572 AND status=1 #почему вы не ограничили status=1 в подзапросах? # вот это кто-то где-то вычитал для какой-то оптимизации # не понимая, что делает AND 1 GROUP BY a.cur ORDER BY null
you make a query that selects all data for all time from both tables, and then you filter the output.
Naturally, the base is choking. besides, in subqueries you collect * ALL data, although you only need to read the records, and not output / process the data
at least you can rewrite it like this:
SELECT count(*) FROM ( select cur /* вместо "*" здесь должно быть нужное поле */ from table1 WHERE status = 1 AND (time > 1468443612608 AND time <= 1468530021572) union all select cur /* вместо "*" здесь должно быть нужное поле */ from table2 WHERE status = 1 AND (time > 1468443612608 AND time <= 1468530021572) ) a GROUP BY a.cur;
I do not know your task and architecture of your base, perhaps - and most likely - you should use JOIN on status=1 with WHERE, instead of UNION ALL
on a local server, you naturally don’t see such errors, simply because you do n’t have enough data on a local server, and there are many data on a production server, this is a typical error of a novice web developer - to assume that if the request is executed quickly on a test database will be great to fly in combat
do not want (or can not) change the query: welcome to the nightmare world of bad database administrators:
you can use where you have enough space. It is necessary to remove garbage from temp, put more hard or change the request so that it does not take too much data.
You can still dump the memory, another six months, hold out without terrible brakes.
PS I'm afraid to imagine that I will see if you show the result of executing SHOW CREATE TABLE
I recommend you a great book: MySQL. Performance Optimization . Buy, borrow, download, get a gift, but read it (not necessarily all, at least relevant to your case chapter), if you want to understand what you are doing.