0

我需要从特定的四个类别中选择“四个不同的随机记录”,然后按升序排序。

我尝试选择 16 个随机记录,然后按 category_id 对它们进行分组

询问:


SELECT * FROM
(
    SELECT 
        id, 
        category_id, 
        description, 
        RAND() AS rnd
    FROM questions
    ORDER BY rnd
    LIMIT 16
) AS temp
GROUP BY temp.category_id
LIMIT 4

结果在某个时刻:


id      category_id     description     rnd
--------------------------------------------------------------
224         1           Question 7      0.004305024635330797
293         2           Question 10     0.006966075866451558
601         3           Question 2      0.001877430828174046
958         4           Question 54     0.0065207639769844375

结果在其他时刻:


id      category_id     description     rnd
--------------------------------------------------------------
230         1           Question 2      0.01622675640157122
310         2           Question 21     0.005430353810480194
159         4           Question 17     0.021778853630441106

问题是并不总是显示我需要修复此查询的四个类别,到目前为止我找不到真正的解决方案。
我需要你的帮助 !
提前致谢 !

4

1 回答 1

1

关键是先选择类别,然后再回到原始数据:

select q.*
from (select category_id, substring_index(group_concat(id order by rand()), ',', 1) as id
      from questions
      group by category_id
      order by rand()
      limit 4
     ) c4 join
     questions q
     on q.id = c4.id
order by category_id

还有其他方法可以做到这一点,例如使用一堆union all语句。但这是通用的,可以轻松更改类别的数量。

于 2013-06-22T00:31:56.513 回答