帮我把这个查询统计优化一下User::where("id", $post['id']) ->with([ 'adviser' => function ($query) { $query->where(['id', 'name']); }, 'job_log' => function ($query) { $query->where(['id', 'sex']); }, 'journal' => function ($query) { $query->select(['id', 'name']); }, 'order' => function ($query) { $query->select([ 'user_id', Db::raw("COUNT(*) AS num"), Db::raw("SUM(CASE WHEN status = 2 THEN 1 END ) AS appropriation_num"), Db::raw("SUM(CASE WHEN status = 2 THEN appropriation_amount END ) AS appropriation_sum"), Db::raw("SUM(CASE WHEN status = 5 THEN 1 END ) AS net_income_num"), Db::raw("SUM(CASE WHEN status = 5 THEN net_income END ) AS net_income_sum"), ]); } ]) ->select(['id']) ->first();
时间: 2023-08-15 11:07:10 浏览: 93
好的,这个查询可以进行如下优化:
```php
User::with([
'adviser' => function ($query) {
$query->select('id', 'name');
},
'job_log' => function ($query) {
$query->select('id', 'sex');
},
'journal' => function ($query) {
$query->select('id', 'name');
},
'order' => function ($query) {
$query->select('user_id', DB::raw("COUNT(*) AS num"),
DB::raw("SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END ) AS appropriation_num"),
DB::raw("SUM(CASE WHEN status = 2 THEN appropriation_amount ELSE 0 END ) AS appropriation_sum"),
DB::raw("SUM(CASE WHEN status = 5 THEN 1 ELSE 0 END ) AS net_income_num"),
DB::raw("SUM(CASE WHEN status = 5 THEN net_income ELSE 0 END ) AS net_income_sum"))
->groupBy('user_id');
}
])
->select('id')
->where('id', $post['id'])
->first();
```
主要的优化如下:
1. 在 with 方法中,对于每个关联模型的查询,只选择需要的字段,避免查询过多的无用字段,提高性能;
2. 在 order 模型的查询中,使用 groupBy 方法来分组计算总数和总和,避免使用 CASE WHEN 语句,提高性能。
阅读全文