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

余生长醉 提交于 2019-11-28 09:33:59

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 ;

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!