我编写了以下MySQL查询,以获取每个用户的收件箱消息以及最后一条消息.
select *, `chat_channel` as `channel`, MAX(id) as max_id from `messages`
where (`message_to` = 2 or `message_from` = 2)
and (`delete_one` <> 2 and `delete_two` <> 2)
group by `channel`
order by `max_id` desc limit 40 offset 0我用的是Laravel方法。
public static function getInboxMessages($user_id, $limit = 40, $offset = 0, $search_key = null)
{
return Message::hasSearch($search_key)->select("*", DB::raw("MAX(id) as max_id"))->where(function ($sql) use (
$user_id
) {
$sql->where('message_to', '=', $user_id);
$sql->orWhere('message_from', '=', $user_id);
})->where(function ($sql) use ($user_id) {
$sql->where('delete_one', '<>', $user_id);
$sql->where('delete_two', '<>', $user_id);
})->with([
'sender' => function ($q) {
$q->select('id', 'uid', 'username', 'full_name', 'picture');
}
])->with([
'receiver' => function ($q) {
$q->select('id', 'uid', 'username', 'full_name', 'picture');
}
])->orderBy('max_id', 'DESC')->groupBy('chat_channel')->offset($offset)->limit($limit)->get();
}但是,当我在phpMyAdmin中运行此查询时,会遇到以下错误.
1055 - SELECT list的表达式#1不是按子句分组,而是包含非聚合列'db.messages.id‘,它在功能上不依赖于GROUP子句中的列;这与sql_mode=only_full_group_by不兼容。
当我直接运行Laravel代码时,我不会收到任何错误,但我确实得到了按预期排序的记录。
发布于 2018-11-14 09:07:34
转到phpMyAdmin -> YourDB -> SQL Tab
使用以下命令:
SET GLOBAL sql_mode = 'ONLY_FULL_GROUP_BY';
这将只为您的sql启用完整组by。
若要还原上述命令更改,请使用:
SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
发布于 2018-11-16 11:17:55
它是用于聚合的mysql的STRICT MODE。注意,当您按某项进行分组并选择另一个非聚合字段时,该字段的值是不正确的100%。聚合字段类似于您要分组的字段,count(field)、sum(field)、...etc。
如果您愿意冒这个风险,请转到config\database.php并将strict => true编辑为false
'prefix' => '',
'strict' => false,
'engine' => null,不建议这样做,您应该使用join在group by select上重新处理查询。
select x from table right join (select gb from table group by gb) as grouped on grouped.gb = table.gb像这样的东西
https://stackoverflow.com/questions/51474107
复制相似问题