Jump to content

Flip/reverse the results of a query already using ORDER BY?


joe92

Recommended Posts

<?php
//get the messages from the database
$messagesID_query = mysql_query("SELECT
				messageID, posterID, messageTime, message
			FROM
				chat_messages
			ORDER BY
				messageTime DESC
			LIMIT
				5
		");

 

I am currently using the above query to get the last 5 messages from a message log. Say we have 45 messages, the query will pull them out like so:

45,

44,

43,

42,

41

 

I then need that order flipped so that I can display the newest message (id, 45) at the bottom of the message box by simply accessing it last. Like so:

41,

42,

43,

44,

45

 

Is there a way I can do all of this in one go with mysql with no need to use any php functions afterwards? I am currently using two loops. One to reverse the order, and another to print the messages in the desired fashion.

 

Many thanks,

Joe

You could wrap a smaller query to reverse the order around the main query.  Like this:


mysql_query("
SELECT * FROM (
SELECT
	messageID, posterID, messageTime, message
FROM
	chat_messages
ORDER BY
	messageTime DESC
LIMIT
	5
) as tbl
ORDER BY
messageTime ASC
");

Archived

This topic is now archived and is closed to further replies.

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