1

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

2 Answers 2

2

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 
Sign up to request clarification or add additional context in comments.

1 Comment

@xtiaan in the order by clause, it test the value of the title whether is it a trash or not, if it is trash it sets a virtual value for the row to 1 otherwise 0 and then sorts them in ascending order. after that, it then sorts the albums.date in descending order.
1

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.