简体   繁体   English

SQL select 语句带随机数

[英]SQL select statement with random number

I'm currently creating some type of quiz website.我目前正在创建某种类型的测验网站。

My plan: Creating a random number in my sql statement to get a random question from my table.我的计划:在我的 sql 语句中创建一个随机数,以从我的表中获取一个随机问题。

Eg every question have a numeric id -> creating random number (max number = records in my table) -> select random question by id例如,每个问题都有一个数字 id -> 创建随机数(最大数量 = 我表中的记录) -> select 随机问题(按 id)

I tried the followed statement:我尝试了以下语句:

SELECT *
FROM question
WHERE ID = (SELECT FLOOR(RAND() * (SELECT COUNT(ID) FROM question)) + 1);

My problem: Sometimes I got no result, sometimes I got two results and sometimes it worked as planed.我的问题:有时我没有结果,有时我得到两个结果,有时它按计划工作。

If I try the SELECT FLOOR etc. on it's own, the random number works perfectly.如果我自己尝试 SELECT FLOOR 等,随机数可以完美运行。

Any suggestions?有什么建议么? Thank you in advance my friends!提前谢谢我的朋友们!

If you don't have very many questions, you can simply do:如果您没有很多问题,您可以简单地执行以下操作:

select q.*
from question q
order by rand()
limit 1;

If you have lots of questions, then reducing the number is important for performance.如果您有很多问题,那么减少数量对性能很重要。 Something like:就像是:

select q.*
from question q cross join
     (select count(*) from q) qq  
where rand() < 100 / q   -- get a sample of about 100
order by rand()
limit 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM