我有消息表: 消息:
Id, Content, Category, createdAt
1, test1, cat1, 2018-03-26 18:22:39
2, test2, cat1, 2018-03-26 18:22:46
3, test3, cat2, 2018-03-26 18:22:52
4, test4, cat2, 2018-03-26 18:23:11
5, test5, cat2, 2018-03-26 18:23:13
6, test6, cat1, 2018-03-26 18:23:17
从这些数据中,我想为每个类别选择 2 行,即 Cat1 和 Cat2,各 2 行。
那么检索此数据的 SQL 查询是什么?这是示例数据,像这样,我有数千行和 20 到 25 个不同的类别。所以我想从每个类别中检索相同数量的行。此外,这些行应根据createdAt 列按升序排列。
预期输出(假设createdAt是最后一行):
Id, Content, Category, createdAt
6, test6, cat1, 2018-03-26 18:23:17
2, test2, cat1, 2018-03-26 18:22:46
5, test5, cat2, 2018-03-26 18:23:13
4, test4, cat2, 2018-03-26 18:23:11
最佳答案
使用动态顶部 您可以使用任何数字代替 N
SELECT Id,Content,Category,createdAt
FROM (SELECT t.*,
CASE
WHEN @category != t.category THEN @rownum := 1
ELSE @rownum := @rownum + 1
END AS rank,
@category := t.category AS var_category
FROM Table1 t
JOIN (SELECT @rownum := NULL, @category := '') r
ORDER BY t.Category,t.createdAt DESC) x
WHERE x.rank <= 'N'
您可以使用任何数字代替 N
输出
ID Content Category createdAt
6 test6 cat1 2018-03-26T18:23:17Z
2 test2 cat1 2018-03-26T18:22:46Z
5 test5 cat2 2018-03-26T18:23:13Z
4 test4 cat2 2018-03-26T18:23:11Z
现场演示
关于mysql - 从每个类别中选择行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49505467/