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

爱⌒轻易说出口 提交于 2019-12-13 03:52:36

问题


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.


回答1:


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()



回答2:


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



来源:https://stackoverflow.com/questions/3990439/sorting-by-some-column-and-also-by-rand-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!