雄辩查询未使用索引

fhity93d  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(237)

我有一个很有说服力的查询(在使用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\u audits有索引,但是查询没有使用它。您建议如何重新编写查询以使用索引?
以防万一,我还附加了生成这个sql查询的雄辩查询。

$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();
mdfafbf1

mdfafbf11#

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

create index idx_aud_created_userid on tbl_audits (created_at, fk_user_id)

相关问题