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

Link to comment
Share on other sites

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
");

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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