我有留言表: 消息:
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
答案 0 :(得分:2)
使用动态顶部 您可以使用任意数字
代替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
现场演示
答案 1 :(得分:1)
由于没有row_Number()函数是MySql,它变得有点棘手。
select
a.Id, a.Content, a.Category, a.createdAt
from Table1 a
JOIN Table1 b ON a.Category = b.Category AND a.createdAt <= b.createdAt
GROUP BY a.Category, a.createdAt
having count(*) <= 2
order by Category, CreatedAt desc
答案 2 :(得分:0)
我猜这个等级正是你要找的
SELECT
(
CASE category
WHEN @curCat
THEN @curRow := @curRow + 1
ELSE @curRow := 1 AND @curCat := category END
) + 1 AS rank,
category,
id,
content
FROM tab1,
(SELECT
@curRow := 0,
@curType := '') r
ORDER BY category
AND rank <= 2;