PHP Order By Multiple Fields in MySQL

Want to be able to order by two or more database fields / columns using the ASC and DESC order clause

You can sort query results in ascending or descending order on one or more of the columns in the result set by using the ASC or DESC keywords with the ORDER BY clause.

Ordering By Two Fields

SELECT * FROM table ORDER BY (field1 / field2) DESC

Ordering By Three Fields

If both field1 and field2 match in more then one row, then use a third to order them by:

SELECT * FROM table ORDER BY (field1 / field2) DESC, field3 DESC

10 Responses

  1. This is a cool explanation… i was looking for that. Thanks

  2. thomas

    this was great! thanks!

  3. rv

    great answer – thanks!

  4. rv

    Actually the above code did not work for me. This does:

    ORDER BY FIELD1,FIELD2 ASC

    (or DESC, etc)

  5. Thanks Alot dear

    Its really working

  6. anyone

    Thanks man I love you :)

  7. thx for the info, but in my case the solution was the use of GREATEST(fieldA,fieldB) as XXX order by XXX…

    i learn it oN this posT ::

    http://teethgrinder.co.uk/perm.php?a=MySQL-max-of-two-columns

    pD :: i hope be useful ;)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Next Post » »