[英]MYSQL SELECT DISTINCT RECORDS GROUPED
I need to select "four distinct random records" from specific four categories and then order by ascending. 我需要从特定的四个类别中选择“四个不同的随机记录”,然后按升序排列。
I tried to select sixteen random records and then I have grouped them by category_id 我尝试选择16条随机记录,然后按category_id将它们分组
Query: 查询:
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
Results in some moment : 片刻结果:
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
Results in other moment : 其他时刻的结果:
id category_id description rnd
--------------------------------------------------------------
230 1 Question 2 0.01622675640157122
310 2 Question 21 0.005430353810480194
159 4 Question 17 0.021778853630441106
The problem is that not always show the four categories I need to fix this query, up to now I can't find the real solution. 问题在于,并非总是显示我需要解决此查询的四个类别,到目前为止,我还没有找到真正的解决方案。
I need your help ! 我需要你的帮助 !
Thanks in advance ! 提前致谢 !
The key is to choose the categories first and then go back to the original data: 关键是要首先选择的类别,然后再回到原来的数据:
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
There are other ways to do this, such as by using a bunch of union all
statements. 还有其他方法可以做到这一点,例如使用一堆并
union all
语句。 But this is general and makes it easy to change the number of categories. 但这很笼统,可以轻松更改类别数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.