Fetching RAND() rows without ORDER BY RAND() in just one query

后端 未结 3 1017
粉色の甜心
粉色の甜心 2020-12-10 00:26

Using RAND() in MySQL to get a single random row out of a huge table is very slow:

SELECT quote FROM quotes ORDER BY RAND() LIMIT 1

Here is

相关标签:
3条回答
  • 2020-12-10 01:01

    Is there a reason why a stored procedure cannot be used to create a prepared statement?

    DELIMITER //
    DROP PROCEDURE IF EXISTS rand_quote//
    CREATE PROCEDURE rand_quote()
    BEGIN
        SET @rand := ROUND((SELECT COUNT(*) FROM quotes) * RAND());
        SET @sql := CONCAT('SELECT * FROM quotes LIMIT ', @rand, ', 1');
        PREPARE stmt FROM @sql;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END;
    //
    DELIMITER ;
    
    0 讨论(0)
  • 2020-12-10 01:05

    I solved the problem by checking max id. Then i made php loop of rand(0, max_id) which checks if object exists. Done.

    Much faster then previous ordering by rand.

    0 讨论(0)
  • 2020-12-10 01:23

    I just figgured this one, that seams like a solution:

    SELECT * FROM quotes
    WHERE quotes_id = ROUND(
      (SELECT COUNT(*) FROM quotes) * RAND()
    )
    LIMIT 1
    

    But it will work only if quotes_id has no gaps.

    0 讨论(0)
提交回复
热议问题