ITPub博客

首页 > 数据库 > MySQL > SQL实现分组limit

SQL实现分组limit

原创 MySQL 作者:孤竹星 时间:2017-02-16 13:30:43 0 删除 编辑
mysql> create table a (id int,fid int ,name varchar(10));
Query OK, 0 rows affected (0.10 sec)

mysql> insert into a value (1,1,'a');
Query OK, 1 row affected (0.04 sec)

mysql> insert into a value (2,1,'b');
Query OK, 1 row affected (0.01 sec)

mysql> insert into a value (3,1,'c'); 
Query OK, 1 row affected (0.01 sec)

mysql> insert into a value (4,2,'d');   
Query OK, 1 row affected (0.02 sec)

mysql> insert into a value (5,2,'e'); 
Query OK, 1 row affected (0.01 sec)

mysql> insert into a value (6,2,'f'); 
Query OK, 1 row affected (0.00 sec)

 mysql> select * from a
    -> ;
+------+------+------+
| id   | fid  | name |
+------+------+------+
|    1 |    1 | a    |
|    2 |    1 | b    |
|    3 |    1 | c    |
|    4 |    2 | d    |
|    5 |    2 | e    |
|    6 |    2 | f    |
+------+------+------+
6 rows in set (0.00 sec)
mysql> select * from a where 2>( select count(*) from a b  where a.fid=b.fid and a.id<b.id )order by fid ;
+------+------+------+
| id   | fid  | name |
+------+------+------+
|    2 |    1 | b    |
|    3 |    1 | c    |
|    5 |    2 | e    |
|    6 |    2 | f    |
+------+------+------+
4 rows in set (0.00 sec)


mysql> select * from a where 2>( select count(*) from a b  where a.fid=b.fid and a.id>b.id )order by fid ;
+------+------+------+
| id   | fid  | name |
+------+------+------+
|    1 |    1 | a    |
|    2 |    1 | b    |
|    4 |    2 | d    |
|    5 |    2 | e    |
+------+------+------+
4 rows in set (0.00 sec)

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/28282660/viewspace-2133644/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: centos6.8安装jdk8
请登录后发表评论 登录
全部评论

注册时间:2013-01-22

  • 博文量
    96
  • 访问量
    298368