mysql - 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,但原始的就可以了。
解决方案
使用row_number()
:
select t.*
from (select t.*, row_number() over (partition by type order by id) as seqnum
from t
) t
where seqnum <= 2;
推荐阅读
- c# - UnityWebRequest(path, UnityWebRequest.kHttpVerbGET):如何在请求中添加变量以检索特定的mysql行?
- powershell - 如何通过 jenkins 使用 powershell 64bit exe 运行 .ps1 脚本?
- java - 如果匿名内部类有两个外部类,如何获取外部类的引用?
- node.js - 带有webpack的节点打字稿捆绑文件找不到ejs文件
- github - 是否可以关闭 GitHub/GitLab 存储库?
- html - 当 div 没有使用 css 的某些类时,如何在 div 中添加元素的样式?
- excel - VBA Excel 饼图绘制,如何选择正确的饼图?
- javascript - 如何检测 Node.js 中的键序列以执行某些操作
- python - 在下拉列表xpath中检索项目文本
- html - Foreach 循环位置无法正常工作