【发布时间】:2019-04-22 14:19:14
【问题描述】:
我正在使用 Laravel 5.6 和 VueJS 构建一个应用程序,从 Laravel 后端的 API 请求数据。在我的 DEV 环境中,查询根本不需要时间,但在生产环境中,API 上的响应需要 85.7 秒,而在 DEV 环境中则需要 0.1 秒。两种环境中的数据相同。
使用控制器中的以下命令,我能够获得运行的确切查询,并且可以一一测试它们:
DB::enableQueryLog();
// then my eloquent stuff
$query = Sportevent::whereHas('photos')->with('photos');
if($request->input('year')){
$year = $request->input('year');
$query = $query->where('date','like', $year.'%');
}
if($request->input('country')){
$country = $request->input('country');
$query = $query->where('country',$country);
}
$sportevents = $query->orderBy('date',"DESC")->paginate(10);
// then I display the queries:
dd(DB::getQueryLog());
以下是生成的查询,未选择年份或国家/地区,包括两种环境中随时间变化的性能:
// --------------------------------------------------------------
// DEV: 0.0208 seconds | PROD: 73 seconds (had to use stopwatch)
// --------------------------------------------------------------
select count(*) as aggregate from `events` where exists
(select * from `photos` where `events`.`id` = `photos`.`eventID`
and `active` = 1)
// ------------------------------------------
// DEV: 0.025 seconds | PROD: 38.9721 seconds
// ------------------------------------------
select * from `events` where exists (select * from `photos` where
`events`.`id` = `photos`.`eventID` and `active` = 1)
order by `date` desc limit 10 offset 0
// ------------------------------------------
// DEV: 0.0112 seconds | PROD: 0.0141 seconds
// ------------------------------------------
select * from `photos` where `active` = 1 and `photos`.`eventID` in
(11194, 11087, 10506, 10797, 9910, 10118, 10212, 9655, 10047, 10049)
表格事件包含大约 6000 个条目和少于 50000 个条目的照片。如果您在表结构方面需要更多详细信息,请在 cmets 部分投票之前告诉我 :-)
在生产服务器上,许多其他应用程序使用 Laravel 或 Wordpress 在相同的 MySQL 安装上使用数据库运行,它们都没有类似的问题。
【问题讨论】:
-
开发和生产数据库不同?如果是,请确保生产中也存在索引。
-
都是一样的,除了id作为主键定义在两个表上没有索引。
-
可能是您的生产服务器数据库引擎配置远低于您的开发环境。尝试联系您的托管服务提供商。
-
它在 VPS 上...所以我应该是我的 MySQL 服务器的主人
-
我刚刚在
photos.eventID列上添加了一个索引,这似乎可以解决问题。现在像火箭一样快...:API 响应 0.4 秒
标签: mysql laravel-5 phpmyadmin eloquent