限制多个id仅在MySQL中显示2行

时间:2019-05-13 03:25:33

标签: mysql limit

如何显示所有数据,但限制相同的id值仅显示2行 例如,这是我的表“ test”:

id  name    created_at
1   a       2019-01-02
1   b       2019-01-03
1   c       2019-01-04
1   d       2019-01-05
1   e       2019-01-06
2   f       2019-01-07
2   g       2019-01-08
2   h       2019-01-09
3   i       2019-01-10
3   j       2019-01-11
3   k       2019-01-12
4   l       2019-01-13

并且我希望输出获取所有数据,但仅限制2行以显示是否具有相同的ID,例如:

id  name    created_at
1   d       2019-01-05
1   e       2019-01-06
2   g       2019-01-08
2   h       2019-01-09
3   j       2019-01-11
3   k       2019-01-12
4   l       2019-01-13

1 个答案:

答案 0 :(得分:0)

WITH Top2 AS (
    SELECT
        Id,
        Name,
        ROW_NUMBER() OVER (PARTITION BY Id) AS RowCount
    FROM Test
)
SELECT
    Id,
    Name
FROM Top2
WHERE RowCount <= 2

已更新了另一种解决方案,我尚未对其进行测试

SET @RowCount = 0;
SET @LId = 0;

SELECT
    T.Id,
    T.Name
FROM (
    SELECT
          @RowCount := CASE WHEN @LId = Id THEN @RowCount + 1 ELSE 1 END AS RowCount,
          @LId := Id AS Id ,
          Name
    FROM Test
    ORDER BY Id
    ) T
WHERE T.RowCount <= 2;