如何从表中随机选择每个类别的25个问题,我有4个类别?

I have a table with questions, i want to select random from each category 25 questions.

The table "questions" looks like that:

The categories are: C PC P PP

id question category answer1 answer2 answer3

Not sure what you mean by i want to select random from each category but you can just fetch 25 question from each category and union them like

select question from sometable where category = 'C' limit 25
union
select question from sometable where category = 'PC' limit 25
union
select question from sometable where category = 'P' limit 25
union
select question from sometable where category = 'PP' limit 25

The easiest way is to use union all with a subquery for each category:

(select * from questions where category = 'C' order by rand() limit 25)
union all
(select * from questions where category = 'PC' order by rand() limit 25)
union all
(select * from questions where category = 'P' order by rand() limit 25)
union all
(select * from questions where category = 'PP' order by rand() limit 25)

If you have a lot of categories or a whole lot of questions (hundreds of thousands or more), then you might want a query that performs better. But for lesser amounts of data, this is probably fine.

I want to emphasize that union all is better for such a query than union. union removes duplicates adding addition processing that should not be needed in this case.

Used an outer query with ORDER BY RAND() to select records which are selected from the inner query in a random fashion.

SELECT * FROM
(
    (SELECT * FROM questions WHERE category='C' ORDER BY RAND() LIMIT 25) T1
    UNION
    (SELECT * FROM questions WHERE category='PC' ORDER BY RAND() LIMIT 25) T2
    UNION
    (SELECT * FROM questions WHERE category='P' ORDER BY RAND() LIMIT 25) T3
    UNION
    (SELECT * FROM questions WHERE category='PP' ORDER BY RAND() LIMIT 25) T4
) TT
ORDER BY RAND()

This is a HINT you can work upon.

SYNTAX: Use this query :

SELECT * FROM `table` WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` )

In place of 'table' put 'questions'.(This is because you have a table name 'questions').

Hope this will help.