如何解决"不在GROUP BY" mysql查询中的错误

时间:2015-11-08 07:10:32

标签: php mysql laravel

我有两个模型:postslikings,它们具有一对多关系(因此,一个帖子有很多喜欢)。 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模式)似乎是不合逻辑的,但查询中的变化最小。

2 个答案:

答案 0 :(得分:9)

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

这是标准行为,在mysql中,取决于ONLY_FULL_GROUP_BY模式 此模式在&gt; = Map<Question, Answer> correct; Map<Question, Answer> actual; int total = actual.entrySet().stream() .filter(e -> e.getValue().equals(correct.get(e.getKey())) .mapToInt(e -> e.getKey().getScore()) .sum(); 中默认启用。

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

aggregate

其他方式 - 更改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

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

  1. 获取汇总和发布ID
  2. 使用已获取的ID(使用SET SESSION sql_mode = '';
  3. 获取帖子数据

答案 1 :(得分:2)

在5.7中,sqlmode默认设置为:

  

ONLY_FULL_GROUP_BY,NO_AUTO_CREATE_USER,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION

要删除ONLY_FULL_GROUP_BY子句,您可以执行此操作:

N