首页 > 解决方案 > MYSQL:为不同的列值获取相同数量的行

问题描述

好的,假设我有这张桌子

表名:“示例”

id | type  | value
-----------------
1  | color | blue
2  | plants| apple
3  | color | red
4  | color | yellow
5  | plants| grapes
6  | things| cellphone

如何进行单个查询(或者可能带有子查询)以返回 2 行(如果数据较少,则返回更少) EACH type

我可以针对单个查询执行此操作:

select * from `example` where `type` = 'color' limit 2

我不能只使用where in因为这不会返回相等数量的结果。

预期结果:(每种类型2个或更少)

id | type  | value
-----------------
1  | color | blue
2  | plants| apple
3  | color | red
5  | plants| grapes
6  | things| cellphone

顺便说一句,我正在使用 laravel eloquent,但原始的就可以了。

标签: mysqlsql

解决方案


使用row_number()

select t.*
from (select t.*, row_number() over (partition by type order by id) as seqnum
      from t
     ) t
where seqnum <= 2;

推荐阅读