我有一个测验系统,其中的问题有多个选择。
我想显示正确的答案以及另外四个错误的选择。总共我必须有五个选择。
表格选择
id | choice | questionid | correct ---+--------+------------+-------- 1 | choice1| 1 | false 2 | choice2| 1 | false 3 | choice3| 1 | false 4 | choice4| 1 | false 5 | choice5| 1 | true 6 | choice6| 1 | false 7 | choice7| 1 | false 8 | choice8| 1 | false
表可能会扩展…
现在,我想选择四个错误答案,然后在问题下方列出正确答案。并且对于每个用户来说,问题的选择应该有所不同。
如何查询表以获取此结果?我不想进行两个查询并将它们绑定到如下数组中:
SELECT * FROM `choices` WHERE questionid = :qid AND correct = true SELECT * FROM `choices` WHERE questionid = :qid AND correct = false AND id IN( SELECT id FROM `choices` ORDER BY RAND() LIMIT 4 )
相反,我认为应该一步一步完成。
SELECT * FROM `choises` WHERE questionid = :qid ORDER BY correct DESC, RAND() LIMIT 5
假设correct是某种int。否则,您可能需要更改DESC为ASC。
correct
DESC
ASC
您可以使用以下一种方法“混洗”这5种结果ORDER BY RAND():
ORDER BY RAND()
SELECT * FROM ( SELECT * FROM `choises` WHERE questionid = :qid ORDER BY correct DESC, RAND() LIMIT 5 ) as t ORDER BY RAND()