Mysql Select some random rows and plus one specific row

后端 未结 1 899
情歌与酒
情歌与酒 2020-12-22 06:51

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.

相关标签:
1条回答
  • 2020-12-22 07:27
    SELECT *
    FROM `choises`
    WHERE questionid = :qid
    ORDER BY correct DESC, RAND()
    LIMIT 5
    

    Assuming correct is some sort of int. Otherwise you might need to change DESC to ASC.

    You can 'shuffle' the 5 results using one more ORDER BY RAND() like this:

    SELECT * FROM (
        SELECT *
        FROM `choises`
        WHERE questionid = :qid
        ORDER BY correct DESC, RAND()
        LIMIT 5
    ) as t
    ORDER BY RAND()
    
    0 讨论(0)
提交回复
热议问题