开发者社区 问答 正文

MySQL不同分类的等量提取问题

比如一个表
12
我想从这个表里面不同cate_id提取title出来,每个cate_id提取2条记录
大家有什么好办法?

展开
收起
落地花开啦 2016-02-11 13:38:30 2314 分享 版权
1 条回答
写回答
取消 提交回答
  • 公益是一辈子的事, I am digoal, just do it. 阿里云数据库团队, 擅长PolarDB, PostgreSQL, DuckDB, ADB等, 长期致力于推动开源数据库技术、生态在中国的发展与开源产业人才培养. 曾荣获阿里巴巴麒麟布道师称号、2018届OSCAR开源尖峰人物.

    这个需要在PostgreSQL中,可以使用窗口查询来满足需求:

    digoal=# create table tbl(id int, cate_id int, title text);
    CREATE TABLE
    digoal=# insert into tbl values (1,1,'a'),(2,1,'b'),(3,2,'c'),(4,2,'d'),(5,2,'e'),(6,3,'f'),(7,3,'g');
    INSERT 0 7
    digoal=# select * from tbl;
     id | cate_id | title 
    ----+---------+-------
      1 |       1 | a
      2 |       1 | b
      3 |       2 | c
      4 |       2 | d
      5 |       2 | e
      6 |       3 | f
      7 |       3 | g
    (7 rows)
    digoal=# select * from (select row_number() over(partition by cate_id) rn,* from tbl) t where rn <=2;
     rn | id | cate_id | title 
    ----+----+---------+-------
      1 |  1 |       1 | a
      2 |  2 |       1 | b
      1 |  3 |       2 | c
      2 |  4 |       2 | d
      1 |  6 |       3 | f
      2 |  7 |       3 | g
    (6 rows)
    2019-07-17 18:40:38
    赞同 展开评论