我有这样的选择:
StoreProduct::where('user_id', Auth::user()->main_id)
->whereNotExists(function($query)
{
$query->select(DB::raw(1))
->from('store_products')
->whereRaw('store_products.store_product_id = store_product.id');
})
->orderBy('id', 'desc')->paginate($perPage)
在我的数据库中有20K行,此选择执行大约65秒。
我正在使用laravel debugbar。查询转储2选择:
select count(*) as aggregate from `store_product` where `store_product`.`deleted_at` is null and `user_id` = '20' and not exists (select 1 from `store_products` where store_products.store_product_id = store_product.id)65.88s
select * from `store_product` where `store_product`.`deleted_at` is null and `user_id` = '20' and not exists (select 1 from `store_products` where store_products.store_product_id = store_product.id) order by `id` desc limit 24 offset 0
为什么laravel会select count(*) as aggregate
?如何优化此查询?