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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With