Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine RAND and DESC in a query

Tags:

php

mysql

I have a query:

$msg_check = mysql_query ("SELECT * FROM msgs WHERE name='$name' ORDER BY replies DESC LIMIT 5");
while($row = mysql_fetch_array($msg_check)) {
$comment = $row['comment'];
$nickname = $row['nickname'];

What I need to do is take 5 comments with most replies and sort them randomly. I've tried by combining RAND with DESC, but failed :/

like image 913
Menel Avatar asked Dec 01 '25 09:12

Menel


2 Answers

You can apply an outer query that uses RAND() in the ORDER BY clause:

SELECT *
FROM (
  SELECT * 
  FROM msgs 
  WHERE name='$name' 
  ORDER BY replies DESC LIMIT 5) AS t
ORDER BY RAND()

Note: It is always preferable to explicitly name each field in the SELECT clause instead of using *.

like image 106
Giorgos Betsos Avatar answered Dec 04 '25 01:12

Giorgos Betsos


Try this

SELECT * FROM 
 (SELECT * FROM msgs where name='$name' ORDER BY replies DESC LIMIT 5) 
 ORDER BY rand()
like image 33
Megan Fox Avatar answered Dec 04 '25 00:12

Megan Fox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!