【发布时间】:2018-11-22 18:53:06
【问题描述】:
我在一个最大的应用程序中工作(超过 100 万用户),我尝试在记分牌部分获取每个用户的排名,但遇到了这个问题:结果非常非常慢
这是我的数据库的架构:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
...
});
Schema::create('topics', function (Blueprint $table) {
$table->increments('id');
...
});
主题表超过 20 行
Schema::create('user_scores', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('topic_id')->unsigned();
$table->unique(['user_id', 'topic_id']);
$table->float('timer');
$table->integer('score');
});
为用户排名的查询
User::where('type',0)->get()->each(function ($user) {
$user->topics= $user->scores->sum('score');
$user->timing= $user->scores->sum('timer');
})->sort(function ($a, $b){
return ($b->topics - $a->topics) == 0
? ($a->timing - $b->timing)
: ($b->topics - $a->topics);
})->values()->each(function($user, $key){
$user->rank = $key +1;
});
我应该进行任何优化以更快地获得结果吗?谢谢。
【问题讨论】:
-
你不能期望每个人都猜测你正在执行什么查询。请举一些例子,否则任何建议都只是一个更好的猜测......
-
你在PHP数组中排序,这就是为什么速度...尝试对数据库中的行进行排序
-
@Alex 请举个例子
标签: php mysql laravel apache laravel-5