Jump to content

select n max record from table


zohab

Recommended Posts

Hi all

 

I have id column in my table

 

id

1

2

3

4

5

6

7

8

9

10

 

Now

i want to select 2end max record from table ,to do this

 

i will do following

 

select max(id) from table where id not in (select max(id) from table).

 

 

but if i want to find 3 max or 5 max or 8 max record from table

 

how can i do this?

 

any ideas?

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/121675-select-n-max-record-from-table/
Share on other sites

Your making it more complicated than it needs to be.

 

Just do this

SELECT id FROM table ORDER BY id DESC LIMIT 3

 

Just change the 3 to however many you want to select.

 

Exactly... Then, to retrieve the specific record you are after, use mysql_result. So, for instance, you want the 5th highest record:

<?php
$sql = mysql_query("SELECT id FROM table ORDER BY id DESC LIMIT 5");
$id = mysql_result($sql, 4, 'id');
?>

 

Remember that results are numbered as arrays, so your 1st record is actually row 0...

 

Hope this helps.

 

**EDIT**

In fact, you could just do this with one query:

 

5th record:

SELECT id FROM table ORDER BY id DESC LIMIT 4, 1;

 

10th record:

SELECT id FROM table ORDER BY id DESC LIMIT 9, 1;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.