mysql - Group By 但指定每个分组 ID 的行数

标签 mysql

我有以下内容:

id | name  | Book Read        | Date Read
1    Maria   Dogs love cats     12/31/2008
1    Maria   Cats and Dogs      12/31/2007
1    Maria   Cowboys            12/31/2006
2    Tom     Cowboys            12/31/2008
2    Tom     Indians            12/31/2005
2    Tom     Cats and Dogs      12/31/2003
3    Harry   Raining hard       12/31/2005
3    Harry   Cats and Dogs      12/31/2002
3    Harry   Indians            12/31/2001

如果我执行“SELECT * FROM table GROUP BY id”,我得到:

id | name  | Book Read         | Date Read
1    Maria   Dogs love cats      12/31/2008
2    Tom     Cowboys             12/31/2008
3    Harry   Raining hard        12/31/2005

但是我如何为每个人获得前 2 本书?即:

id | name  | Book Read         | Date Read
1    Maria   Dogs love cats      12/31/2008
1    Maria   Cats and Dogs       12/31/2007
2    Tom     Cowboys             12/31/2008
2    Tom     Indians             12/31/2005
3    Harry   Raining hard        12/31/2005
3    Harry   Cats and Dogs       12/31/2002

最佳答案

假设你有一个自增字段,在我的例子中叫做 i

select * from table as t1
where (select count(*) from table as t2
       where t1.id = t2.id and t2.i < t1.i) <2

这是另一种选择

select tmp.i,tmp.id,tmp.name,tmp.book_read
from (
  select 
    id,i,name,book_read,
    if( @prev <> id, @r:=1,@r:=@r+1 ) as rank,
    @prev := id
  from table as t
  join (select @r:=null,@prev:=0) as rn
  order by t.id,t.i
) as tmp
where tmp.rank <= 2
order by i,id; 

关于mysql - Group By 但指定每个分组 ID 的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6316231/

相关文章:

html - 在mysql中将两个结果集合并为一个

php - 计算表中行数的最有效方法是什么?

MySQL:获取所有匹配行的计数以及结果集

php - [PHP-MYSQL]报表查询

php - 使用 fetch_assoc 从数据集中获取特定行?

mysql - 慢速依赖子查询的问题

python - sqlalchemy:无需密码即可连接到 MySQL

Mysql:如何正确生成当前一组数字上不存在的唯一10位随机数

PHP/MYSQL - 找不到此代码发送邮件两次以上的原因

MySQL:更新并发