【问题标题】:MYSQL: Fetch same number of rows for different column valuesMYSQL:为不同的列值获取相同数量的行
【发布时间】:2021-01-15 03:20:40
【问题描述】:

好吧,假设我有这张桌子

表名:“示例”

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

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

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

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,但原始的也可以。

【问题讨论】:

标签: mysql sql


【解决方案1】:

使用row_number():

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

【讨论】:

  • (partition by type order by id) as seqnum from t ) t where seqnum &lt;= 2;附近有语法错误
  • @IamL 其余的错误信息会给你提示你的 MySQL 版本不支持窗口函数
猜你喜欢
  • 2018-07-22
  • 1970-01-01
  • 2021-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-30
  • 2014-03-25
相关资源
最近更新 更多