口才不使用索引

时间:2018-11-21 10:32:46

标签: mysql sql laravel eloquent

我有一个雄辩的查询,该查询(转换为SQL后)如下:

 SELECT COUNT(*) AS AGGREGATE
    FROM `tbl_audits`
    WHERE `created_at` BETWEEN '2018-09-01 00:00:00' AND '2018-10-31 23:59:59' 
    AND `auditable_type` IN ('App\Models\Offer', 'App\Models\AdvertiserContact') 
    AND `fk_user_id` IN ('10250')

表tbl_audits具有索引,但是查询未使用它。 您如何建议重新编写查询以使用索引?

以防万一我还附加了生成此SQL查询的Eloquent查询。

$logs = Audit::with(array( 'user', 'auditable' ))
        ->whereBetween('created_at', [ "{$start_date} 00:00:00", "{$end_date} 23:59:59" ]);

    if ( $auditLogTypes && $auditLogTypes !== 'null' )
    {
        $auditLogTypesQuery = explode(',', $auditLogTypes);
    }

    if ( in_array(Offer::class, $auditLogTypesQuery) && $offers && $offers !== 'null' )
    {
        $logs->whereIn('auditable_id', explode(',', $offers));
    }

    $logs->whereIn('auditable_type', $auditLogTypesQuery);

    if ( $users && $users !== 'null' )
    {
        $logs->whereIn('fk_user_id', explode(',', $users));
    }

    // count the total data for datatables
    $totalData = $logs->count();

    if ( !$exportToCSV )
    {
        $logs->skip($start)
            ->take($length);
    }

    $logs = $logs->orderBy('created_at', 'DESC')
        ->get();

1 个答案:

答案 0 :(得分:0)

如果不存在,则可以尝试创建这样的复合索引:

create index idx_aud_created_userid on tbl_audits (created_at, fk_user_id)