简体   繁体   中英

Custom MYSQL Custom Sort Order

I have a simple media gallery that sorts the albums based on date as seen in the code example. In amongst the albums I have a "Trash" album for deleted media. How do I keep the ORDER BY albums.date DESC but always set the "Trash" album to be the very last in the order? The album is in column "title" and is always called "trash".

Thanks for your help...

$query = mysql_query("SELECT albums.*,photos.path FROM albums LEFT JOIN photos ON albums.albumCover=photos.id WHERE albums.user='$siteUserID' ORDER BY albums.date DESC");

you can take advantage of the CASE on ORDER BY clause

SELECT...
FROM...
WHERE..
ORDER BY   (CASE 
               WHEN albums.title = 'TRASH'
               THEN 1
               ELSE 0
           END ) ASC, albums.date DESC

You will need to use an ORDER BY CASE which assigns a higher number to the Trash values, hence sorting them later than others. Values not Trash get a zero, and Trash gets a 1. The zeros sort first!

SELECT
  albums.*,
  photos.path
FROM 
  albums
  LEFT JOIN photos ON albums.albumCover=photos.id 
WHERE albums.user='$siteUserID' 
ORDER BY
  CASE WHEN albums.title = 'Trash' THEN 1 ELSE 0 END,
  /* Then suborder the zeros and ones by date */
  albums.date DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM