我有一个多选题的答案表。所以你有三列
ID正确和答案。 ID是自动增量正确是0或1. 0表示错误答案,1表示反向(正确答案)。
我需要以随机顺序选择4行(或者只能以随机顺序调用它们)3必须是不正确的,第4行必须是正确的。
这可以在一个查询中实现吗?
答案 0 :(得分:2)
如果answers
表中的行数相当少,那么你可以这样做
SELECT id, question_id, correct, answer
FROM answers
WHERE question_id = 1
AND correct = 1
UNION ALL
(
SELECT id, question_id, correct, answer
FROM answers
WHERE question_id = 1
AND correct = 0
ORDER BY RAND()
LIMIT 3
)
ORDER BY RAND()
注意: RAND()
中的ORDER BY
操作成本非常高
示例输出:
| ID | QUESTION_ID | CORRECT | ANSWER | |----|-------------|---------|----------| | 7 | 1 | 0 | answer7 | | 10 | 1 | 0 | answer10 | | 5 | 1 | 1 | answer5 | | 4 | 1 | 0 | answer4 |
这是 SQLFiddle 演示