我有一个测验系统,问题有多个选择。
我想表明正确的答案加上四个错误的选择。我必须有五个选择。
表格选择
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
)
相反,我应该一步完成。
答案 0 :(得分:2)
SELECT *
FROM `choises`
WHERE questionid = :qid
ORDER BY correct DESC, RAND()
LIMIT 5
假设correct
是某种int。否则,您可能需要将DESC
更改为ASC
。
您可以使用另外一个ORDER BY RAND()
来“混乱”5个结果:
SELECT * FROM (
SELECT *
FROM `choises`
WHERE questionid = :qid
ORDER BY correct DESC, RAND()
LIMIT 5
) as t
ORDER BY RAND()