douyouqian8550 2011-11-29 17:31
浏览 69

随机MySQL查询? 或随机化结果?

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. 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.

Is it possible to do this in MySQL or would I have to use PHP to do it?

  • 写回答

2条回答 默认 最新

  • drh78568 2011-11-29 17:32
    关注

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

     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:

    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. It is a fast way to generate random numbers on demand that is portable between platforms for the same MySQL version.


    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. This avoids scanning the full table.

    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)