我有两个模型:帖子和喜欢有一对多的关系(所以,一个帖子有很多喜欢). 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模式)是不合逻辑的,但查询中的变化最小.
应对每个非聚合字段进行分组.
原文链接:https://www.f2er.com/php/137895.html它是标准行为,在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个查询: