我正在使用Laravel 5.2和MySQL 5.6.33
当我通过应用dd(DB::getQueryLog());
检查数据库查询时,它返回如下:
array:14 [▼
0 => array:3 [▼
"query" => "select count(*) as aggregate from `products` where exists (select * from `agents` where `products`.`agent_id` = `agents`.`id`) and exists (select * from `productlocations` where `productlocations`.`product_id` = `products`.`id` and `town_id` = ?) and exists (select * from `productagents` where `productagents`.`product_id` = `products`.`id` and `product_status_id` = ?)"
"bindings" => array:2 [▼
0 => "674"
1 => "1"
]
"time" => 22286.26
]
1 => array:3 [▼
"query" => "select * from `products` where exists (select * from `agents` where `products`.`agent_id` = `agents`.`id`) and exists (select * from `productlocations` where `productlocations`.`product_id` = `products`.`id` and `town_id` = ?) and exists (select * from `productagents` where `productagents`.`product_id` = `products`.`id` and `product_status_id` = ?) order by `id` desc limit 10 offset 0"
"bindings" => array:2 [▼
0 => "674"
1 => "1"
]
"time" => 38.4
]
2 => array:3 [▼
"query" => "select * from `agents` where `agents`.`id` in (?)"
"bindings" => array:1 [▶]
"time" => 0.58
]
你可以看到结果,"计数"查询已完成22286ms,但过滤数据的相同查询只花了38.4ms。我需要在哪里查看以加快此查询的速度?需要更改DB还是Eloquent?
编辑:
explain
select * from `products` where exists
(select * from `agents` where `products`.`agent_id` = `agents`.`id`)
and exists
(select * from `productlocations` where `productlocations`.`product_id` = `products`.`id` and `town_id` = 674)
and exists
(select * from `productagents` where `productagents`.`product_id` = `products`.`id` and `product_status_id` = 1)
order by `id` desc limit 10 offset 0
答案 0 :(得分:0)
我发现了我的错误。列agent_id
应在products
表
答案 1 :(得分:0)
使用此查询来计算主键,而不是*将使您比*
更快SELECT FROM raw re WHERE re.class_ids LIKE (regex)