Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last record in MySql with 2.5m rows

I want to get the last record in my MySql table, but the table has 2.5 million rows. How to get the last row efficiently?

I'm using order and limit but the query runs ~15sec. I have to decrease this value to nearly zero.

My SQL Query :

SELECT id FROM table1 WHERE scenedevice_id = X AND module_id = Y ORDER BY id DESC LIMIT 0,1

EDIT : I tried MAX(id) also.

EDIT : Here is my table -

CREATE TABLE IF NOT EXISTS `realtimedevicedata` (
  `id` int(11) NOT NULL auto_increment,
  `scenedevice_id` int(11) NOT NULL,
  `module_id` int(11) NOT NULL,
  `subid` tinyint(4) NOT NULL default '1',
  `value` varchar(30) collate utf8_turkish_ci NOT NULL,
  `timestamp` datetime NOT NULL,
  PRIMARY KEY  (`id`),
  KEY `scenedevice_id` (`scenedevice_id`),
  KEY `module_id` (`module_id`),
  KEY `timestamp` (`timestamp`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci AUTO_INCREMENT=2428598 ;

Thanks.

like image 710
totten Avatar asked Aug 16 '12 08:08

totten


People also ask

How do I get the last row in MySQL?

To get the last record, the following is the query. mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1; The following is the output. The above output shows that we have fetched the last record, with Id 4 and Name Carol.

How do I get the last 3 rows of a SQL table?

Try only this:- SELECT * FROM reset ORDER BY ASC LIMIT (FOUND_ROWS() - 3), 3 and check if it is giving the last 3 rows from your table in ascending order!!!

How do I get the last 5 rows of a SQL table?

METHOD 1 : Using LIMIT clause in descending order As we know that LIMIT clause gives the no. of specified rows from specifies row. We will retrieve last 5 rows in descending order using LIMIT and ORDER BY clauses and finally make the resultant rows ascending.

How do I select the last two rows in SQL?

To select last two rows, use ORDER BY DESC LIMIT 2.


3 Answers

Try

SELECT MAX(id)
FROM table1
like image 81
John Woo Avatar answered Oct 27 '22 00:10

John Woo


I create an index for two coloumns scenedevice_id and module_id, and execution time is now 0ms :)

Thank you for all help, folks :)

like image 32
totten Avatar answered Oct 27 '22 01:10

totten


Just another way

select * from TableName where ColumnID = (Select max(ColumnID) from TableName)
like image 42
mmrs151 Avatar answered Oct 27 '22 02:10

mmrs151