开发者

Getting random values in mySql query

开发者 https://www.devze.com 2022-12-29 20:53 出处:网络
I have a query which selects 6 names in the database. eg SELECT names FROM users LIMIT 6 Now I want this query to select a random 6 names in the database table, is this possible? And how开发者_如何

I have a query which selects 6 names in the database. eg

SELECT names FROM users LIMIT 6

Now I want this query to select a random 6 names in the database table, is this possible? And how开发者_如何学Go


The simple but slow solution is:

SELECT names FROM users ORDER BY RAND() LIMIT 6

This uses sorting on a random number and has O(n log n) performace. It should run fine for say 10000 rows, but for larger tables it won't scale well.

To get it faster you can look at Quassnoi's article MySQL: selecting a number of random rows fast.

SELECT  *
FROM    (
        SELECT  @cnt := COUNT(*) + 1,
                @lim := 6
        FROM    users
        ) vars
STRAIGHT_JOIN
        (
        SELECT  names,
                @lim := @lim - 1
        FROM    users r
        WHERE   (@cnt := @cnt - 1)
                AND RAND() < @lim / @cnt
        ) i

This has O(n) performance.


SELECT names 
FROM users 
ORDER BY RAND() 
LIMIT 6 


Here is a other quick solution

Select names from users WHERE RAND() LIMIT 6
0

精彩评论

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