mariadb mysql查询以检索每个项目类型的前2条记录

fcg9iug3  于 2022-11-08  发布在  Mysql
关注(0)|答案(5)|浏览(197)

我有一张table

rowid    item      item title
1        pen       pen 1
2        pen       pen 2
3        pencil    pencil 1
4        pencil    pencil 2
5        pen       pen 3
6        paper     paper 1
7        pencil    pencil 3
8        paper     paper 2
9        paper     paper 3

我需要一个查询,可以在mysql输出这样的

rowid    item      item title
1        pen       pen 1
2        pen       pen 2
6        paper     paper 1
8        paper     paper 2
3        pencil    pencil 1
4        pencil    pencil 2

我的意思是,对于每个不同的项目,查询需要输出前2个项目标题,也请给我查询
获取每个项目的最后10行或n行,而不是前2行

zzzyeukh

zzzyeukh1#

请尝试以下查询:

select @rn := 1, @itemLag := '';

select rowid, item, itemTitle from (
    select rowid, 
           case when @itemLag = item then @rn := @rn + 1 else @rn := 1 end rn, 
           @itemLag := item, 
           item, 
           itemTitle
    from tbl
    order by item, rowid
) a where rn <= 2

Demo

kzmpq1sx

kzmpq1sx2#

这是一个最适合分析函数的问题,比如行号和排名。但是,由于您的MariaDB版本不支持它们,我们必须找到一个解决方法。
一种不需要任何动态SQL的方法是创建一个查询,该查询查找每个项目组的最小值和次小值rowid。然后,我们只需将原始表连接到该子查询,以便仅保留前两个匹配行。

SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT a.item, b.min_rowid, MIN(a.rowid) AS next_min_rowid
    FROM yourTable a
    INNER JOIN
    (
        SELECT item, MIN(rowid) AS min_rowid
        FROM yourTable
        GROUP BY item
    ) b
        ON a.item = b.item
    WHERE a.rowid > b.min_rowid
    GROUP BY a.item, b.min_rowid
) t2
    ON t1.item = t2.item AND (t1.rowid = t2.min_rowid OR t1.rowid = t2.next_min_rowid)
ORDER BY
    t1.item, t1.rowid;

Demo(第一个字母)

xqk2d5yq

xqk2d5yq3#

我将使用带有LIMIT子句的相关子查询:

SELECT t.*
FROM table t
WHERE rowid IN (SELECT t1.rowid 
                FROM table t1
                WHERE t1.item = t.item
                ORDER BY t1.itemtitle
                LIMIT 2 
               );

如果您需要最新的itemtitle,则执行ORDER BY t1.itemtitle DESC,并使用10n修改LIMIT子句。

ktca8awb

ktca8awb4#

假设每个项目至少有两行,这将是可行的:

select t.*
from t
where t.rowid <= (select t2.rowid
                  from t2
                  where t2.item = t.item
                  order by t2.rowid
                  limit 1, 1
                 );

您可以使用coalesce()来行程只有一列的项目:

select t.*
from t
where t.rowid <= coalesce( (select t2.rowid
                            from t2
                            where t2.item = t.item
                            order by t2.rowid
                            limit 1, 1
                           ),
                           t.rowid
                         );
d7v8vwbk

d7v8vwbk5#

select 
  *,
  row_number() over (partition by item order by rowid asc) as rank 
  from yourtable
  qualify rank <= 2

相关问题