如何组合两个select, UNION All, rand()的结果



有一个表,其中包含一些答案。其中一个答案为真(字段tf=1),另外几个答案为假(字段tf=0)。如何随机选择1个正确答案和N个错误答案?结果必须是随机的。这是我的例子,它工作,但真实的答案总是在第一行:

(SELECT * FROM answers where tf=1 and `questionsid`=1 limit 1)
UNION all
(SELECT * FROM answers where tf=0 and `questionsid`=1 order by rand() limit 5 )

谢谢。顺便说一下,我有另一个解决方案,也有效:

(SELECT *, rand() as t FROM answers where tf=1 and `questionsid`=1 limit 1)
UNION all
(SELECT *, rand() as t FROM answers where tf=0 and `questionsid`=1 order by rand() limit 5 )
order by t

如果没有任何样本数据,这是未经测试的,但是假设你可以用外部select包装你的查询,所以在选择一个正确答案和5个额外的随机错误答案后,返回所有6再次随机排序:

select * from (
(select * 
from answers 
where tf=1 and questionsid=1 
limit 1)
union all
(select * 
from answers 
where tf=0 and questionsid=1 
order by Rand() 
limit 5)
)r
order by rand()

最新更新