Good day. I am tasked with trying to speed up some slow running queries, but being a MYSQL newbie I'm not sure if I have achieved the best possible result. I realize the forum is littered with these types of questions already and I have read through a lot of them, but I would still appreciate some further assistance if that is possible.
I started the optimizing procedure by stripping away the joins and first trying to speed up the basic select. The table has about 4 400 000 entries in it, and the query returns in the region of 1 800 000 entries.
I started with this:
select
ID,
CallStarted,
CallDirection
from
TRMSMain.tblcalldata CALLDATA
where CallStarted BETWEEN '2014-02-10' AND '2014-05-11 23:59:59'
ORDER BY ID DESC LIMIT 0 , 50;
It took about 360 seconds. This, however took 2 seconds:
select
ID,
CallStarted,
CallDirection
from
TRMSMain.tblcalldata CALLDATA
where CallStarted BETWEEN '2014-02-10' AND '2014-05-11 23:59:59'
LIMIT 0 , 50;
Although the last query returned the first 50 in the range, instead of the last 50, it led me to believe that the "order by desc" operation is very expensive. I then fiddled around a bit and came up with the following (which of course is not the only way to have done it), which takes anywhere from 20 to (sometimes) 40 seconds:
use trmsmain;
RESET QUERY CACHE;
drop procedure if exists intTest;
delimiter #
create procedure intTest()
BEGIN
declare lastID int unsigned default 0;
declare frstID int unsigned default 0;
select
(select max(ID) from trmsmain.tblcalldata where (CallStarted BETWEEN '2014-02-10' AND '2014-05-11 23:59:59'))
into lastID;
set frstID = lastID - 49;
CREATE TEMPORARY TABLE IF NOT EXISTS table2 (index (ID)) AS
(
select
ID,
CallStarted,
CallDirection
from
trmsmain.tblcalldata CALLDATA
where
ID between frstID AND lastID
);
select * from table2 order by ID desc;
END #
delimiter ;
call intTest();
The results are exactly what I need, and callstarted is an indexed field, but my question is if this kind of performance is acceptable (the best I can expect). My PC is mid range with 4GB of Ram.
Please advise. Thank you.
MORE INFO:
My SQL script equates to this:
select
ID,
CallStarted,
CallDirection
from trmsmain.tblcalldata CALLDATA
where ID between (select(select max(ID) from trmsmain.tblcalldata where (CallStarted BETWEEN '2014-02-10' AND '2014-05-11 23:59:59')) - 49) AND
(select max(ID) from trmsmain.tblcalldata where (CallStarted BETWEEN '2014-02-10' AND '2014-05-11 23:59:59'));
I only did it the way I did because I wanted to see if the above would re-use the result of MAX, so I compared the result of the above to that of the script (which was similar).
After I looked at he explain, I was confused and removed all the indexes except for the one on callstarted. ID is the primary key.
Having only the one index brought the time down to one second. Even when using "force index(callstarted) I could not come close to this result.
I am somehow confused even further now.
Regards