I have a table consisting of: items, a ranking score and the number of votes a user has cast on it. For simplicity: id, ranks, votes.
I'm trying to run a query which sorts items from highest ranking score to lowest, unless the number of votes = 0.
Because I have a base ranking score for new items, ordering my ranking isn't possible.
I've tried the following, along with some other permutations:
$list = $dbh->query('SELECT * FROM ranks ORDER BY votes desc, rating desc case when min(votes)= 0 else rating desc');
to no avail, after looking at : Conditional sorting in MySQL and Conditional sorting in MySQL?
I tried this:
SELECT * FROM ranks ORDER BY rating desc, case votes when 0 then votes end
This is the table, and the output I get:
ID : Rating : Votes
2 : 201 : 9
3 : 100 : 0
4 : 100 : 0
5 : 100 : 0
1 : -13 : 9
My ideal output would be:
ID : Rating : Votes
2 : 201 : 9
1 : -13 : 9
4 : 100 : 0
5 : 100 : 0
3 : 100 : 0
As you can see, this doesn't group all the 0 voted items to the end.
I'm sure this is forehead slappingly simple, I'd really appreciate any pointers and best practices. Cheers!
Introduction to MySQL CASE expression Generally speaking, you can use the CASE expression anywhere that allows a valid expression e.g., SELECT , WHERE and ORDER BY clauses.
Although it is most often used there, CASE is not limited to SELECT statements. For example, you can use it in clauses like IN , WHERE , HAVING , and ORDER BY . Using a CASE statement in a query once doesn't mean you have hit your quota for using it. You can use it multiple times in a single query.
SQL order by case can be used when we have to order the data on a conditional basis and define the criteria on which the ordering will be done based on a certain condition.
SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]; You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort that column should be in the column-list.
This group all 0's to end.
SELECT * FROM `ranks` ORDER BY (Votes=0), Rating DESC
QUERY
SELECT *
FROM ranks
ORDER BY case votes
WHEN 0 THEN 0
ELSE 1 END DESC, rating DESC
What the ORDER BY section is saying is:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With