6

I have the table courses where we have some fields and also the field course(string), favorited(bool), favoritedDate(dateTime), dateUpload.

The teacher uploads the course and this date is stored in the dateUpload field. If the teacher flag this course as favorite this information is a number 1 in the field favorited and the date it was flagged is stored in the field favoritedDate.

Now I need to retrieve all courses from a specific teacher and then order the list by date: If the course is flagged favorited=1 should ordered by favoritedDate,dateUpload desc, if favorited=0 should be ordered only by dateUpload desc.

This is what I have so far but it is not working:

SELECT * from courses where teacherId = 23 
ORDER BY 
 CASE favorited WHEN 1 THEN favoritedDate, dateUpload
 else dateUpload
 END
 DESC
;

Any idea how to solve this?

asked Mar 19, 2018 at 18:52
0

2 Answers 2

5

A case expression returns an atomic value so you can't return:

favoritedDate, dateUpload

I think this will do what you want:

ORDER BY
 CASE favorited WHEN 1 THEN favoritedDate 
 ELSE dateUpload 
 END DESC, dateUpload
answered Mar 19, 2018 at 19:02
6

As Lennart explains, a CASE expression in MySQL can only produce a single value, not two or more. I think this would suite your problem:

ORDER BY
 CASE WHEN favorited = 1 THEN 0 ELSE 1 END,
 CASE WHEN favorited = 1 THEN favoritedDate END,
 dateUpload DESC ;

If the favoritedDate values are NULL when the item is not "favourited", then you really don't need the favorited column at all. The information is stored in favoritedDate: If it's null, it's not a favourite. If it's not null, it is. The ORDER BY in that case (not much simpler, due to MySQL sorting nulls before not null values):

ORDER BY
 (favoritedDate IS NULL),
 favoritedDate,
 dateUpload DESC ;
answered Mar 19, 2018 at 19:19
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.