I have a database table which is being updated every second. I would like to make write a query that pulls the most recent 20,000 records (about 6 hours worth, since it's collected every second).
I thought to try:
SELECT time_stamp, column2, column3
FROM myDB.table1
limit 20000;
But the above query pulls the items from the very beginning of when the data was inserted into the table. I would like the most recent 20000 records.
What would be the query to pull the most recent records inserted into a table?
The correct query is:
SELECT time_stamp, column2, column3
FROM myDB.table1
ORDER BY time_stamp DESC
LIMIT 20000;
However, you might find that the query is expensive. If you have an index on time_stamp
, you might find this more efficient:
SELECT time_stamp, column2, column3
FROM myDB.table1
WHERE time_stamp >= date_sub(now(), interval 6 hours);
It is not exactly 20,000 records, but it is the most recent records and it should be faster than sorting all the data.
You can create such an index by doing:
create index idx_table1_timestamp on table1(time_stamp);
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.