我有两个模型:posts
和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-config(可能会删除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
或者,你可以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
:
SET SESSION sql_mode = '';
此外,您可以将其划分为2个查询:
- 获取聚合ID和发布ID
- 使用提取的ID获取posts数据(使用
IN clause
)
在5.7中,sqlmode默认设置为:
ONLY_FULL_GROUP_BY,NO_AUTO_CREATE_USER,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
要删除子句ONLY_FULL_GROUP_BY,可以执行以下操作:
SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));