How to request a random row in SQL?

前端 未结 29 2950
孤城傲影
孤城傲影 2020-11-21 06:45

How can I request a random row (or as close to truly random as is possible) in pure SQL?

相关标签:
29条回答
  • 2020-11-21 07:10

    If possible, use stored statements to avoid the inefficiency of both indexes on RND() and creating a record number field.

    PREPARE RandomRecord FROM "SELECT * FROM table LIMIT ?,1";
    SET @n=FLOOR(RAND()*(SELECT COUNT(*) FROM table));
    EXECUTE RandomRecord USING @n;
    
    0 讨论(0)
  • 2020-11-21 07:10

    As pointed out in @BillKarwin's comment on @cnu's answer...

    When combining with a LIMIT, I've found that it performs much better (at least with PostgreSQL 9.1) to JOIN with a random ordering rather than to directly order the actual rows: e.g.

    SELECT * FROM tbl_post AS t
    JOIN ...
    JOIN ( SELECT id, CAST(-2147483648 * RANDOM() AS integer) AS rand
           FROM tbl_post
           WHERE create_time >= 1349928000
         ) r ON r.id = t.id
    WHERE create_time >= 1349928000 AND ...
    ORDER BY r.rand
    LIMIT 100
    

    Just make sure that the 'r' generates a 'rand' value for every possible key value in the complex query which is joined with it but still limit the number of rows of 'r' where possible.

    The CAST as Integer is especially helpful for PostgreSQL 9.2 which has specific sort optimisation for integer and single precision floating types.

    0 讨论(0)
  • 2020-11-21 07:12

    For SQL Server 2005 and above, extending @GreyPanther's answer for the cases when num_value has not continuous values. This works too for cases when we have not evenly distributed datasets and when num_value is not a number but a unique identifier.

    WITH CTE_Table (SelRow, num_value) 
    AS 
    (
        SELECT ROW_NUMBER() OVER(ORDER BY ID) AS SelRow, num_value FROM table
    ) 
    
    SELECT * FROM table Where num_value = ( 
        SELECT TOP 1 num_value FROM CTE_Table  WHERE SelRow >= RAND() * (SELECT MAX(SelRow) FROM CTE_Table)
    )
    
    0 讨论(0)
  • 2020-11-21 07:13

    For MySQL to get random record

     SELECT name
      FROM random AS r1 JOIN
           (SELECT (RAND() *
                         (SELECT MAX(id)
                            FROM random)) AS id)
            AS r2
     WHERE r1.id >= r2.id
     ORDER BY r1.id ASC
     LIMIT 1
    

    More detail http://jan.kneschke.de/projects/mysql/order-by-rand/

    0 讨论(0)
  • 2020-11-21 07:13
     SELECT * FROM table ORDER BY RAND() LIMIT 1
    
    0 讨论(0)
  • 2020-11-21 07:14

    A simple and efficient way from http://akinas.com/pages/en/blog/mysql_random_row/

    SET @i = (SELECT FLOOR(RAND() * COUNT(*)) FROM table); PREPARE get_stmt FROM 'SELECT * FROM table LIMIT ?, 1'; EXECUTE get_stmt USING @i;
    
    0 讨论(0)
提交回复
热议问题