sql查询按问题分组

ru9i0ody  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(350)

我编写了下面的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

我用的拉威尔方法。。。

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不在group by子句中,并且包含未聚合的列'db.messages.id',该列在功能上不依赖于group by子句中的列;这与sql\u mode=only\u full\u group by不兼容
当我直接运行laravel代码时,我没有收到任何错误,但我确实得到了按预期排序的记录。

hgtggwj0

hgtggwj01#

这是最重要的 STRICT MODE 用于聚合的mysql。请注意,当您按某个内容分组并选择另一个非聚合字段时,该字段的值不是100%正确的。聚合字段类似于要分组的字段, count(field) , sum(field) 等等
如果你愿意冒这个风险,去 config\database.php 并编辑 strict => truefalse ```
'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

像这样的

yhuiod9q

yhuiod9q2#

phpMyAdmin -> YourDB -> SQL Tab 使用以下命令: SET GLOBAL sql_mode = 'ONLY_FULL_GROUP_BY'; 这将只为您的sql启用完全分组。
要还原上述命令更改,请使用: SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

相关问题