简体   繁体   English

随机MySQL查询? 还是将结果随机化?

[英]Random MySQL Query? Or randomize a result?

So, I want to pull a query on a MySQL database, however, I want the result to be randomized - that is, I don't want the same thing to come up in the same order every time. 因此,我想对MySQL数据库进行查询,但是,我希望结果是随机的-也就是说,我不想每次都以相同的顺序出现同一件事。 This is because I will only be listing the first 6 items of the query (or 2 items, in some cases), and I want all the contents of the database to have a chance to appear. 这是因为我将只列出查询的前6个项目(在某些情况下为2个项目),并且希望数据库的所有内容都有机会出现。

Is it possible to do this in MySQL or would I have to use PHP to do it? 是否可以在MySQL中执行此操作,还是我必须使用PHP来执行此操作?

For a fast approach try this: 快速方法请尝试以下操作:

SELECT  *
FROM    (
        SELECT  @cnt := COUNT(*) + 1,
                @lim := 10
        FROM    t_random
        ) vars
STRAIGHT_JOIN
        (
        SELECT  r.*,
                @lim := @lim - 1
        FROM    t_random r
        WHERE   (@cnt := @cnt - 1)
                AND RAND(20090301) < @lim / @cnt
        ) i

See this article for a detailed description of how it works: 请参阅本文以获取有关其工作原理的详细说明:


A simpler (but slow way) is to use ORDER BY RAND() : 一种更简单(但很慢的方法)是使用ORDER BY RAND()

 SELECT *
 FROM yourtable
 ORDER BY RAND()
 LIMIT 6

From the manual : 手册

... you can retrieve rows in random order like this: ...您可以按以下随机顺序检索行:

 mysql> SELECT * FROM tbl_name ORDER BY RAND(); 

ORDER BY RAND() combined with LIMIT is useful for selecting a random sample from a set of rows: 结合LIMIT的ORDER BY RAND()可用于从一组行中选择随机样本:

 mysql> SELECT * FROM table1, table2 WHERE a=b AND c<d -> ORDER BY RAND() LIMIT 1000; 

RAND() is not meant to be a perfect random generator. RAND()并不是完美的随机生成器。 It is a fast way to generate random numbers on demand that is portable between platforms for the same MySQL version. 这是一种根据需要生成随机数的快速方法,该随机数可在同一MySQL版本的平台之间移植。


If you have a unique id field which is incrementing from 1 to n without any gaps you can improve performance even more by choosing six random numbers in [1, n] and fetching the six rows with those ids. 如果您具有从1到n递增且没有任何间隙的唯一id字段,则可以通过选择[1,n]中的六个随机数并使用这些id提取六行来进一步提高性能。 This avoids scanning the full table. 这样可以避免扫描整个表。

Mark Byers is correct this has been asked before. 马克·拜尔斯(Mark Byers)是对的,之前已经有人问过。

You want to put your random algorithm at the application layer vs the database layer. 您想将随机算法放在应用程序层与数据库层之间。 There is a huge performance hit at the database layer (assuming MySQL). 在数据库层(假设MySQL)会极大地影响性能。 Doing it at the application layer will involve some extra coding but you will find it is much more flexible as you can update the algorithm to suit your latest business needs, not to mention you can implement optimizations such as caching. 在应用程序层执行此操作将涉及一些额外的编码,但是您会发现它更加灵活,因为您可以更新算法以适合最新的业务需求,更不用说可以实现诸如缓存之类的优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM