如何选择每个类别的有限数据

huangapple go评论89阅读模式
英文:

How to select limited data per category

问题

我有一个名为Category的表,如下所示:

Id    Name
1     A
2     B

我还有一个名为Product的表,如下所示:

Id   Name    Category_id
1    C       1
2    D       1
3    E       1
4    F       2
5    G       2
6    H       2

我想从每个类别中选择2个项目。我正在应用以下查询:

从产品中选择Product.id,Product.name as pname,category.name as cname,加入类别,其中Category_id=Category.id限制0,4

但它返回了产品表的前四个数据,如下所示:

Product.id    Pname    Cname
1             C        A
2             D        A
3             E        A
4             F        B

但我想要从每个类别中获取2个产品:

Product.id    Pname    Cname
1             C        A
2             D        A
4             F        B
5             G        B
英文:

I have a table named Category like

Id    Name
1     A
2     B

And i have product table like

Id   Name    Category_id
1    C       1
2    D       1
3    E       1
4    F       2
5    G       2
6    H       2

I want to select 2 items from each category. I am applying this query

Select Product.id,Product.name as pname,category.name as cname from product join category where Category_id=Category.id limit 0,4

But it's returning first four data of the product table like

Product.id    Pname    Cname
1             C        A
2             D        A
3             E        A
4             F        B

But i Want to get 2 product from each category

Product.id    Pname    Cname
1             C        A
2             D        A
4             F        B
5             G        B

答案1

得分: 1

如果您正在运行MySQL 8.0,您可以使用 row_number()

select p.id pid, name, p.name pname, c.name cname
from (
    select p.*, row_number() over(partition by category_id order by id) rn from product p
) p
inner join category c on c.id = p.category_id
where p.rn <= 2
英文:

If you are running MySQL 8.0, you can use row_number():

select p.id pid, name, p.name pname, c.name cname
from (
    select p.*, row_number() over(partition by category_id order by id) rn from product p
) p
inner join category c on c.id = p.category_id
where p.rn &lt;= 2

huangapple
  • 本文由 发表于 2020年1月6日 18:01:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/59610041.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定