简体   繁体   English

Mysql选择一些随机行和一个特定行

[英]Mysql Select some random rows and plus one specific row

I have a quiz system which questions have multiple choises. 我有一个测验系统,问题有多个选择。

I want to show the right answer plus four more wrong choices. 我想表明正确的答案加上四个错误的选择。 Totally I must have five choices. 我必须有五个选择。

Table choices 表格选择

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

Table may be extended... 表格可能会延长......

Now I want to select four wrong answers and the correct answer to list below the question. 现在我想选择四个错误答案,并在问题下方列出正确答案。 And for each user sees the question choices should be different. 并且对于每个用户看到的问题选择应该是不同的。

How can I query the table for this result? 如何在表中查询此结果? I do not want to make two queries and bind them in an array like below: 我不想做两个查询并将它们绑定在如下所示的数组中:

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
            )

Instead it should be done with one step I guess. 相反,它应该完成一步我想。

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

Assuming correct is some sort of int. 假设correct是某种int。 Otherwise you might need to change DESC to ASC . 否则,您可能需要将DESC更改为ASC

You can 'shuffle' the 5 results using one more ORDER BY RAND() like this: 您可以使用另外一个ORDER BY RAND()来“混乱”5个结果,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM