【发布时间】:2021-02-13 10:59:49
【问题描述】:
我正在尝试使用 groupBy 方法获取最大值并在日期创建。
但是当我放入 created_at 列时,我得到了一个错误。
$rankings = Ranking
::select(DB::raw('MAX(rankings.percentage_correct_answer) as percentage_correct_answer, rankings.user_id,rankings.created_at'))
->groupBy('rankings.user_id')
->get();
错误:
SQLSTATE[42000]:语法错误或访问冲突:1055 'app.rankings.created_at' 不在 GROUP BY 中(SQL:选择 MAX(rankings.percentage_correct_answer) 作为 percent_correct_answer、rankings.user_id、rankings。 created_at 来自rankings,其中rankings.deleted_at 为空组rankings.user_id)
但是,我通过拉出 created_at 列做得很好。为什么?
而我想获取 created_at 列,我该怎么办?
这段代码没有错误。
$rankings = Ranking
::select(DB::raw('MAX(rankings.percentage_correct_answer) as percentage_correct_answer, rankings.user_id'))
->groupBy('rankings.user_id')
->get();
型号代码:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Ranking extends Model
{
use SoftDeletes;
protected $table = 'rankings';
protected $fillable = [
'user_id','percentage_correct_answer'
];
}
排行榜说明:
+---------------------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| user_id | bigint(20) unsigned | NO | | NULL | |
| percentage_correct_answer | int(11) | NO | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
| deleted_at | timestamp | YES | | NULL | |
+---------------------------+---------------------+------+-----+---------+----------------+
【问题讨论】:
-
使用
groupBy时,所有非聚合列都应从select中排除。或者需要找到一种方法来聚合这些列。