Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select last 20 order by ascending - PHP/MySQL

Tags:

php

mysql

This is my table structure

MyTable
ID[P.K][auto increment]   TopicID   UID   Comment

Now i want to get the last 20 comment for a TopicID but it should be sorted in ascending order !

[Just like Facebook by default shows last 20 comment only]

I am looking for an optimized version, i can do this with 2/3 query and php sort array, but looking for some better alternative

Sample Result with data

MyTable  
ID TopicID UID Comment  
1  1       10  AAAA   
2  1       11  BBBB  
3  1       10  CCCC  
4  1       10  dddd   
5  1       11  EEEE  
6  1       10  FFFF

I want to get the last 3 result for a TopicID, the result should be

4  1       10  dddd   
5  1       11  EEEE  
6  1       10  FFFF

and not

6  1       10  FFFF  
5  1       11  EEEE  
4  1       10  dddd  
like image 312
Sourav Avatar asked May 06 '11 14:05

Sourav


2 Answers

First, select last 20 entries. Then sort them in ascending order. You can easily do this in a single query (with subquery):

select * from (
    select * from your_table order by id desc limit 20
) tmp order by tmp.id asc
like image 176
binaryLV Avatar answered Sep 23 '22 15:09

binaryLV


SELECT  *
FROM    (
        SELECT  *
        FROM    mytable
        WHERE   topicid = $mytopicid
        ORDER BY
                id DESC
        LIMIT 20
        ) q
ORDER BY
        id

or, more efficiently,

(
SELECT  *
FROM    mytable
WHERE   topicid = $mytopicid
ORDER BY
        id DESC
LIMIT 20
)
ORDER BY
        id
like image 5
Quassnoi Avatar answered Sep 22 '22 15:09

Quassnoi