Jump to content

MYSQL multiple ORDER BY fields


Troy2000
Go to solution Solved by Psycho,

Recommended Posts

I have been looking for an answer to a problem with sorting all day and cannot seem to find the correct answer.  The following is my sql query:

 

SELECT Id, zone, xtime, xdate, temp, status FROM temp_log WHERE zone LIKE 'Unit%' ORDER BY Id DESC LIMIT 3

 

I know that the last 3 entries will contain the 3 units and I always get the last 3 entries in the table, however, I cannot seem to get the order correct. :

 

sometimes:

Unit03

Unit01

Unit02

 

or:

Unit01

Unit03

Unit02

 

sometimes it is the way I want it:

Unit01

Unit02

Unit03

 

What do I need to add to the query to get the zone names in the correct order?  Or possibly a better way of doing what I want to do.

 

Thanks,

 

Troy

 

Link to comment
Share on other sites

I tried this:

 

ORDER BY zone ASC, Id DESC LIMIT 3

or just:

ORDER BY zone, Id DESC LIMIT 3

 

Which gives me:

Unit01

Unit01

Unit01

 

ORDER BY Id DESC LIMIT 3, zone ASC 

or just:

ORDER BY Id DESC LIMIT 3, zone

 

I get: error Undeclared variable: zone

 

Am I not sorting by zone correctly?

 

Thanks

 

Troy

Link to comment
Share on other sites

  • Solution

You are trying to use ORDER BY in two different ways - one to get the last three records that have been added and another one to sort them for display purposes - you can't do both concurrently. You can use a subquery to get the last three records and an outer query to sort them for display purposes

SELECT *
FROM (
    SELECT Id, zone, xtime, xdate, temp, status
    FROM temp_log
    WHERE zone LIKE 'Unit%'
    ORDER BY Id DESC
    LIMIT 3
) unitResults
ORDER BY zone
Edited by Psycho
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.