LIMIT then RAND rather than RAND then LIMIT

こ雲淡風輕ζ 提交于 2020-01-04 02:54:21

问题


I'm using full text search to pull rows.
I order the rows based on score (ORDER BY SCORE) , then of the top 20 rows (LIMIT 20), I want to rand (RAND) the result set.

So for any specific search term, I want to randomly show 5 of the top 20 results.

My workaround is code based- where I put the top 20 into an array then randomly select 5.

Is there sql way to do this?


回答1:


You can do this using an inner select. Select the top twenty rows in the inner select. In the outer select order these rows randomly and select the top five:

SELECT *
FROM (
    SELECT *
    FROM table1
    ORDER BY score DESC
    LIMIT 20
) AS T1
ORDER BY RAND()
LIMIT 5


来源:https://stackoverflow.com/questions/2648076/limit-then-rand-rather-than-rand-then-limit

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