如何限制每组的行数?
我正在使用mysql。我不关心返回多少组,但如果单个组有超过 4 个项目,我只想要前 4 个。如何编写每组仅返回 4 行的语句?作为临时修复,我只是将它们全部返回并在代码中将其过滤掉。它仍然相当快,尽管如果我知道语法会更容易
I am using mysql. I don't care how many groups get returned back but if a single group has more then 4 items i only want the first 4. How do i write a statement that only returns 4rows per group? As a temporary fix i am just returning them all and filtering it out in code. Its still pretty fast although it would be easier if i knew syntax
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我正确理解您的问题,我相信以下答案应该大致满足您的需要(注意:由于未提供您的表结构,我已经包含了两个测试表及其关联的插入作为示例):
给定这些表和数据:
以下 SQL 将按客户选择购买数据,返回不超过 4 次最近的购买:
以下是此选择的结果输出(请注意,Alex 最旧的交易不存在):
If I understand your question correctly, I believe the following answer should do approximately what you need (note: I've included two test tables and their associated inserts as an example since your table structure was not provided):
Given these tables and data:
The following SQL will select purchase data by customer returning no more than the 4 most recent purchases:
Here is the resulting output from this select (note that Alex's oldest transactions are absent):