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

时间:2014-05-08 11:36:44

标签: php mysql

我有一个问题表,我想从每个类别25个问题中随机选择。

“问题”表格如下:

类别为:C PC P PP

id问题类别answer1 answer2 answer3

4 个答案:

答案 0 :(得分:2)

最简单的方法是将union all与每个类别的子查询一起使用:

(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)

如果您有很多类别或大量问题(数十万或更多),那么您可能需要一个性能更好的查询。但是对于较少量的数据,这可能很好。

我想强调union all对于这样的查询比union更好。 union删除重复项,添加在这种情况下不需要的添加处理。

答案 1 :(得分:0)

不确定i want to select random from each category你的意思,但你可以从每个类别中获取25个问题并将它们联合起来像

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

答案 2 :(得分:0)

使用带有ORDER BY RAND()的外部查询来选择以随机方式从内部查询中选择的记录。

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()

答案 3 :(得分:0)

这是您可以使用的HINT

<强>语法: 使用此查询:

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

代替'table' put 'questions'。(这是因为你有一个表名'问题')。

希望这会有所帮助。