开发者

Sorting by some column and also by rand() in MySQL

Is it possible to sort a result set by some column and also by RAND()?

For example:

  SELECT `a`, `b`, `c` 
    FROM `table` 
ORDER BY `a开发者_运维问答` DESC, RAND() 
   LIMIT 0, 10

Thank you.


What you are doing is valid - it will order the results in descending order by a but randomize the order of ties.

However to do what you want you need to first use a subquery to get the latest 100 records and then afterwards sort the results of that subquery randomly using an outer query:

SELECT * FROM
(
    SELECT * FROM table1
    ORDER BY date DESC
    LIMIT 100
) T1
ORDER BY RAND()


I know this is old but I discovered ... Example:

select photo.sort_order, profile.description is not null as desc_order, profile.description, rand() as r from photo photo, profile profile order by photo.sort_order desc, desc_order desc, r ASC

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜