1

I have a database with rated items in it. When I want to display all the items from a specific category and sort the results by rate than by number of likes, it's easy and it's working:

$query =  "SELECT * FROM infos WHERE category = '".$categories."'";
$query .= "ORDER BY `rate` DESC, `like` DESC";

The problem is when the results have the same value, they show up in alphabetical order. So, I would like to randomize the database before I sort it by rate and like. I just want to let the same chance to all items and those that have the same value not to be advantaged by alphabetical order.

I tried this, but it didn't work:

$query =  "SELECT * FROM infos WHERE category = '".$categories."'";
$query .= "ORDER BY RAND(), ORDER BY `rate` DESC, `like` DESC";

Can somebody help me? I'm stuck.

3
  • What didn't work? What was the result of your query? Commented Jun 15, 2013 at 20:35
  • 1
    @zeantsoi It results in a MySQL syntax error - that should have been caught and reported. Commented Jun 15, 2013 at 20:37
  • Make sure to 1) test queries on the CLI or "SQL Studio"; 2) correctly handle errors in SQL queries from PHP; and 3) use placeholders/prepared statements. Commented Jun 15, 2013 at 20:38

1 Answer 1

4

You should turn it around:

SELECT * FROM infos WHERE category=...
ORDER BY rate DESC, like DESC, RAND();

That way it sorts by rate, then like and finally random if rate and like are equal.

Also your original ORDER BY with RAND() doesn't work because you use two ORDER BY clauses.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it's working! First, I tried to remove one of the ORDER BY, but it randomized all my results. If I put the RAND() at the end of my query, it's working like a charm!

Your Answer

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.