加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 如何在mysql查询中解决“不在GROUP BY中”错误

发布时间:2020-12-13 13:34:46 所属栏目:PHP教程 来源:网络整理
导读:我有两个模型:帖子和喜欢有一对多的关系(所以,一个帖子有很多喜欢). Likings模型还有一个isActive字段,表示喜欢是主动还是被动. 我想获得(排序)前5个帖子,这些帖子已经收到了最大的“活跃”喜欢(只有喜欢其isActive字段为true的帖子才会被考虑). 这是查询:
我有两个模型:帖子和喜欢有一对多的关系(所以,一个帖子有很多喜欢). Likings模型还有一个isActive字段,表示喜欢是主动还是被动.

我想获得(排序)前5个帖子,这些帖子已经收到了最大的“活跃”喜欢(只有喜欢其isActive字段为true的帖子才会被考虑).

这是查询:

select posts.*,count(likings.id) as likes_count from 'posts'
left join 'likings' on 'likings'.'post_id' = 'posts'.'id' and 'likings'.'isActive' = 1
group by 'posts'.'id'
order by 'likes_count' desc 
limit 5

这是由这个laravel查询产生的:

Post::selectRaw('posts.*,count(likes.id) as likes_count')
    ->leftJoin('likes',function ($join) {
        $join->on('likes.post_id','=','posts.id')
             ->where('likes.is_active',1);
    })
    ->groupBy('posts.id')
    ->orderBy('likes_count','desc')
    ->take(5)
    ->get();

这是错误:

SQLSTATE[42000]: Syntax error or access violation: 1055
'database.posts.user_id' isn't in GROUP BY

这里,posts.user_id也是posts表的一个字段,并显示帖子的所有者.

我该如何解决这个错误?似乎改变mysql配置(可能删除ONLY_FULL_GROUP_BY模式)是不合逻辑的,但查询中的变化最小.

应对每个非聚合字段进行分组.

它是标准行为,在mysql中,取决于ONLY_FULL_GROUP_BY模式.
此模式在> = 5.7中默认启用.

select posts.id,post.user_id,count(likings.id) as likes_count
from posts
left join likings on likings.post_id = posts.id and likings.isActive= 1
group by posts.id,posts.user_id
order by likes_count desc 
limit 5

或者,您可以聚合它:

select posts.id,MIN(post.user_id),count(likings.id) as likes_count
from posts
left join likings on likings.post_id = posts.id and likings.isActive= 1
group by posts.id
order by likes_count desc 
limit 5

其他方式 – 更改sql_mode:

SET SESSION sql_mode = '';

此外,您可以将其分为2个查询:

>获取聚合和后期ID>使用获取的ID获取帖子数据(使用IN子句)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读