说我在表格中有以下数据:
date_added category
15/10/2009 Novels
12/10/2009 Novels
12/10/2009 Novels
11/10/2009 Novels
17/10/2009 Films
16/10/2009 Films
15/10/2009 Films
15/10/2009 Films
etc.
我希望SQL(Mysql)查询只返回每个类别中的第一行(比如说)2行,即
15/10/2009 Novels
12/10/2009 Novels
17/10/2009 Films
16/10/2009 Films
答案 0 :(得分:0)
这在MySQL中很棘手。我建议使用变量:
select q.*
from (select q.*,
(@rn := if(@c = category_id, @rn + 1,
if(@c := category_id, 1, 1)
)
) as rn
from questions q cross join
(select @rn := 0, @c := -1) params
order by category_id rand()
) q
where rn <= 5;
子查询随机枚举每个类别的问题。然后外部查询为每个类别选择前五个。
答案 1 :(得分:0)
(我不是很擅长mysql。我已经试了一下。)
uuid()功能每次都会生成通用唯一标识符。
ORDER BY RandomID 将为随机选择提供技巧,因为每次运行查询时,RandomID都将是uqique。因此,RandomID ASC或DESC的订单每个都会完全随机地记录该记录。
LIMIT 只会显示5条记录。
最终代码:
SELECT q.question_id, q.Question, c.category_id, uuid() AS RandomID
FROM Question q
INNER JOIN Category c
ON q.Category_id=c.Category_id
ORDER BY RandomID ASC
LIMIT 5
;