I have a MySQL database running on an Ubuntu box that pings 250 clients once a minute (24×7). My column names are:
ip_address varchar(16),
status varchar(7),
timestamp datetime
Been running it for several weeks and it has grown (10,581,421+ rows). I run a query to return the most recent 800 results on a specific IP address:
SELECT *
FROM (
SELECT Device_ip, Status, timestamp
FROM ping_results
where Device_ip = '192.168.1.1'
order by timestamp desc
LIMIT 800
) SUB ORDER BY timestamp asc;
It takes 10+ seconds to return the results. Is there anything I can do differently to speed this up?
Best Answer
Looking at the query, I see you need to retrieve the 800 most recent pings in ascending order.
You should be able to improve the query with the following index
This will help your query in the following manner
ORDER BY
is quickly reduced to a backward index scan on a specificdevice_ip
Give it a Try !!!
UPDATE 2014-11-03 16:05 EST
If the ping_results table has an
id
column, you could probably redo the query using JOINAfter making the index I suggested, you should run the explain plan against this query and your original query. Then, select the best explain plan or the fastest running query. Chances are, you first query should be adequate because it has "less noise" to deal with in the Query Optimizer.
BTW I use LEFT JOIN because the id value will stay in the order is was made from the subquery. Doing INNER JOIN will do an inadvertent reorder of the keys.