【问题标题】:How do I limit results to 10 customers for each status in MySQL如何将 MySQL 中每个状态的结果限制为 10 个客户
【发布时间】:2021-09-15 06:10:57
【问题描述】:

我有一个带有 status_id 和 statuses 表的客户表。我可能有几个状态,每个状态最多需要 10 个客户。

select * from customers
join statuses on customers.status_id = statuses.id
where statuses.id in (18, 19, 20)

在哪里添加限制?尝试弄乱子查询,但我没有取得太大进展。

在转向 eloquent 之前,只是想了解如何在 MySQL 中做到这一点。

【问题讨论】:

  • 您显示 SQL 查询。你可以添加你的代码吗?你如何在 SQL 中做到这一点,你可以在网上找到,不是吗?如何在 Eloquent 中限制查询,您可以在 laravel 文档中找到比在此处提问更快的方法
  • 请您添加生成此查询的代码。
  • 指定精确 MySQL版本。
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: mysql laravel eloquent


【解决方案1】:

只是想了解如何在 MySQL 中做到这一点

with cte As (
    select *, row_number() over (partition by statuses.id order by ???) rownumber
    from customers
    join statuses on customers.status_id = statuses.id
    where statuses.id in (18, 19, 20)
)
select * 
from cte 
where rownumber <= 10;

需要 MySQL 8+。

【讨论】:

  • 这很好用。我想我将其更改为按 customers.status_id 进行分区,但这成功了。
猜你喜欢
  • 1970-01-01
  • 2011-01-01
  • 1970-01-01
  • 2014-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-07
  • 2010-10-01
相关资源
最近更新 更多