tags:

views:

316

answers:

3

I am doing easy web based chat so I need to get (for example) 30 latest messages from a MySQL database. That doesn't make any problem but how can I take the data in up side down order? I mean, the oldest message is the first. I have to take latest 30 records by added time.

EDIT: Thanks for the answers, but...

ORDER BY added DESC LIMIT 30

gives:

15, 14, 13, 12, 11

...and I need:

11, 12, 13, 14, 15

I know I can get it using a subquery. Is there any better method?

A: 

Assuming you have a column called MessageTimestamp that holds a timestamp of each message:

SELECT [...] FROM MyChatTable ORDER BY MessageTimestamp DESC LIMIT 30
Anders Fjeldstad
+1  A: 

I don't see any way to do it without the sub-query, but it should not be a problem. The outer ORDER BY sorts only 30 rows, so performance loss of that will be negligible.

SELECT * FROM
(
  SELECT *
  FROM posts
  ORDER BY post_time DESC
  LIMIT 0, 30
) x
ORDER BY post_time ASC

Of course you should use the actual culumn-names instead of *.

Peter Lang
@James Goodwin: I don't think I get what you mean. The op wants the `30 latest messages`, with `the oldest meassage is the first`. Feel free to post a better solution though :)
Peter Lang
I was thinking the problem was simpler than it actually was, using a sub-query seems to be the only way to achieve this.
James
@James Goodwin: You're welcome :)
Peter Lang
Does my down-voter care to explain if there is anything wrong with my answer?
Peter Lang
A: 

As mentioned above, a simple "desc" sort gets the oldest 30 messages, not the newest (though they are in the right order).

Actually all you need is:

(select col from table order by added desc limit 30) order by added asc

I hope this helps.

Phil Wallach