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
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;

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.