Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

Select last 20 order by ascending - 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  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...