我在MySQL中有一个包含列名category
的表。
我正在尝试编写一个查询,它将从每个category
返回2个随机记录。
以下是我用来从category
列中具有最高值的每个rating
获取2条记录的代码:
SELECT e1.*
FROM entries AS e1
WHERE (SELECT Count(*)
FROM entries AS e2
WHERE e2.category = e1.category
AND e1.rating <= e2.rating) <= 2
ORDER BY category,
rating DESC
检查此链接以查看包含一些示例数据和上述查询的表格: http://sqlfiddle.com/#!9/bab8e/1
答案 0 :(得分:1)
通过按类别列和随机数对表格进行排序,我达到了您想要的结果。然后,我为每一行分配了一个递增编号,每次在类别更改时从1开始。然后我只返回rowNum小于或等于2的结果。如果你想返回3个随机行,你只需将它改为小于或等于3,依此类推。
SELECT entry_id,
category,
rating
FROM (SELECT @currank := IF(@category = category, @currank + 1, 1) AS rowNum,
@category := category AS categoryVar,
e1.*
FROM (SELECT *,
(SELECT @currank := 0) r
FROM entries
ORDER BY category,
Rand()) AS e1)AS e2
WHERE rownum <= 2
ORDER BY category,
rating;
以下是您在问题中发布的sqlfiddle链接: http://sqlfiddle.com/#!9/bab8e/37/0
请注意,可以轻松调整此相同查询以返回一组非随机的记录。例如,如果您想要从每个rating
返回前5 category
,您可以更改
ORDER BY category,rand()
到
ORDER BY category, rating DESC
并改变
WHERE rownum <= 2
到
WHERE rownum <= 5