MYSQL SELECT DISTINCT RECORDS GROUPED

时间:2013-06-21 23:35:36

标签: mysql select group-by distinct

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

我尝试选择十六个随机记录,然后按照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

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

1 个答案:

答案 0 :(得分: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语句。但这是一般性的,可以很容易地改变类别的数量。