数据库 随机取记录

2025-3-26 / 0 评论 / 4 阅读

select top 10 * from tablename order by newid()
select * from tablename order by rand() limit 10

取1条

SELECT description FROM question ORDER BY RAND() LIMIT 1
在ORDER BY从句里面不能使用RAND()函数,因为这样会导致数据列被多次扫描。

SELECT description FROM question WHERE id >= (SELECT FLOOR(RAND() * (SELECT MAX(id) FROM question))) ORDER BY id LIMIT 1

SELECT description FROM question AS t1 JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM question)) AS id) AS t2 WHERE t1.id >= t2.id ORDER BY t1.id ASC LIMIT 1