![](/img/trans.png)
[英]How to count the number of grouped rows in mysql when I already count the total rows
[英]How to get rows grouped by with total count (MySQL, Laravel)
背景
我们的 mysql 数据库中有这个表lead_activity
,具有以下字段
1. id
2. lead_id
3. activity
行示例:
ID | 线索ID | 活动 |
---|---|---|
1 | 5 | 叫 |
2 | 5 | 出售 |
3 | 6 | 已联系 |
4 | 9 | 已联系 |
在 Laravel 中,我有以下查询:
$this->data['lead_activities'] = LeadActivity::select(DB::Raw('count(*) as total'), 'activity')->groupBy('activity')->get();
有了这个结果:
[
0 => [
'total' => 1,
'activity' => 'Called'
],
1 => [
'total' => 1,
'activity' => 'Selled'
],
2 => [
'total' => 2,
'activity' => 'Contacted'
],
]
请求我如何构建此查询(无论是 Eloquent 还是原始 SQL),因此在一个查询中具有与这些结果类似的内容,之后每个查询都没有:
[
0 => [
'total' => 1,
'activity' => 'Called',
'lead_ids' => [5]
],
1 => [
'total' => 1,
'activity' => 'Selled'
'lead_ids' => [5],
],
2 => [
'total' => 2,
'activity' => 'Contacted',
'lead_ids' => [6,9]
],
]
看看 MySQL GROUP_CONCAT() function。
我认为这应该可以解决您的问题。 它不会返回一个lead_ids 数组,而是所有lead_ids 的串联(字符串),之后您可以使用(最终转换为数组)。
$list = LeadActivity::select(DB::Raw('count(*) as total'), 'activity','GROUP_CONCAT(lead_id) as lead_id_aggr')
->groupBy('activity')
->get();
参考: https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat
你可以试试这个:
LeadActivity::query()
->select(
'activity',
DB::raw('GROUP_CONCAT(lead_id) as leads'),
DB::raw('COUNT(*) as activities_count'),
)->groupBy('activity')
->get();
这将产生这个结果:
Illuminate\Database\Eloquent\Collection {#2057
all: [
App\Models\LeadActivity {#2059
activity: "Called",
leads: "5",
activities_count: 1,
},
App\Models\LeadActivity {#2060
activity: "Contacted",
leads: "6,9",
activities_count: 2,
},
App\Models\LeadActivity {#2061
activity: "Sold",
leads: "5",
activities_count: 1,
},
],
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.