quick selection of a random row from a large table in mysql

前端 未结 24 1760
旧时难觅i
旧时难觅i 2020-11-22 09:30

What is a fast way to select a random row from a large mysql table?

I\'m working in php, but I\'m interested in any solution even if it\'s in another language.

24条回答
  •  情话喂你
    2020-11-22 09:50

    Quick and dirty method:

    SET @COUNTER=SELECT COUNT(*) FROM your_table;
    
    SELECT PrimaryKey
    FROM your_table
    LIMIT 1 OFFSET (RAND() * @COUNTER);
    

    The complexity of the first query is O(1) for MyISAM tables.

    The second query accompanies a table full scan. Complexity = O(n)

    Dirty and quick method:

    Keep a separate table for this purpose only. You should also insert the same rows to this table whenever inserting to the original table. Assumption: No DELETEs.

    CREATE TABLE Aux(
      MyPK INT AUTO_INCREMENT,
      PrimaryKey INT
    );
    
    SET @MaxPK = (SELECT MAX(MyPK) FROM Aux);
    SET @RandPK = CAST(RANDOM() * @MaxPK, INT)
    SET @PrimaryKey = (SELECT PrimaryKey FROM Aux WHERE MyPK = @RandPK);
    

    If DELETEs are allowed,

    SET @delta = CAST(@RandPK/10, INT);
    
    SET @PrimaryKey = (SELECT PrimaryKey
                       FROM Aux
                       WHERE MyPK BETWEEN @RandPK - @delta AND @RandPK + @delta
                       LIMIT 1);
    

    The overall complexity is O(1).

提交回复
热议问题