Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve "isn't in GROUP BY" error in mysql query

Tags:

php

mysql

laravel

I have two models: posts and likings which have one-to-many relationship (so, one post has many likes). Likings model has also an isActive field which shows liking is active or passive.

I want to get (sort) top 5 posts which had received maximum "active" likes (only likes whose isActive field is true would be considered).

This is the query:

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

which is resulted from this laravel query:

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();

And this is the error:

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

Here, posts.user_id is also a field of posts table and shows the owner of the post.

How can I resolve this error? It seems it isn't logical to change mysql config (probably deleting ONLY_FULL_GROUP_BY mode), but minimum change in the query.

like image 816
horse Avatar asked Nov 08 '15 07:11

horse


2 Answers

Each non-aggregated field should be grouped.

It is standard behavior, which in mysql, depends on ONLY_FULL_GROUP_BY mode.
This mode is default enabled in >= 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

Or, you can aggregate it:

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

Other way - change sql_mode:

SET SESSION sql_mode = '';

Also, you can divide it to 2 query:

  1. Get aggregate and post ids
  2. Get posts data with fetched ids (with IN clause)
like image 172
vp_arth Avatar answered Oct 09 '22 11:10

vp_arth


In 5.7 the sqlmode is set by default to:

ONLY_FULL_GROUP_BY,NO_AUTO_CREATE_USER,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION

To remove the clause ONLY_FULL_GROUP_BY you can do this:

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
like image 42
Raugaral Avatar answered Oct 09 '22 11:10

Raugaral