MySQL: Can you specify a random limit?

半城伤御伤魂 提交于 2021-02-05 09:39:41

问题


Is there a way to randomize a limit number in SQL (MySQL)?

What I'd like to be able to do is get a random number of results in a query to use in an insertion subquery without any server-side scripting. The query I'd love to be able to run as a hypothetical illustration is:

SELECT id FROM users ORDER BY RAND() LIMIT RAND() * 1000

Of course that doesn't work, but is there another way to randomize the limit number? There are plenty of examples of randomizing a limited set of results, but I can't find anything on the net about setting a random limit.


回答1:


How about this:

    SELECT * 
      FROM users
     ORDER BY RAND()
     HAVING RAND() * 1000 < 10

The clause WHERE RAND() * 1000 < 10 randomly chooses to include each row with a probability of 1%. It's not quite a LIMIT variable clause but will do roughly the same thing.




回答2:


For MySQL specifically:

SET @i = 0;
SELECT * 
FROM users
WHERE (@i:=@i+1) < RAND()*1000
ORDER BY RAND();


来源:https://stackoverflow.com/questions/20748817/mysql-can-you-specify-a-random-limit

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