0

我有一个测验系统,其中的问题有多个选择。

我想展示正确的答案以及另外四个错误的选择。总共我必须有五个选择。

表选择

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
            )

相反,我猜应该一步完成。

4

1 回答 1

2
SELECT *
FROM `choises`
WHERE questionid = :qid
ORDER BY correct DESC, RAND()
LIMIT 5

假设correct是某种 int。否则您可能需要更改DESCASC.

您可以使用类似这样的另一个“洗牌”5 个结果ORDER BY RAND()

SELECT * FROM (
    SELECT *
    FROM `choises`
    WHERE questionid = :qid
    ORDER BY correct DESC, RAND()
    LIMIT 5
) as t
ORDER BY RAND()
于 2013-11-08T16:09:45.690 回答