Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
899 views
in Technique[技术] by (71.8m points)

mysql - A.* isn't in GROUP BY with left join on laravel query builder

   $search_alls=
    DB::table('a16s as A')
    ->select('A.id')
    // ->select('A.*')
    ->addSelect(DB::raw('SUM(CASE WHEN B.approve = 1 ELSE 0 END) as Yshow'))
    ->leftjoin('a16s_likes as B', function($join) {
        $join->on('A.id', '=', 'B.p_id');
        })
    ->groupBy('A.id')
    ->get();

when I use above select('A.id') is work well.

But when I use select('A.*') to select all A cloumn I got the error

SQLSTATE[42000]: Syntax error or access violation: 1055 'employee.A.name' isn't in GROUP BY 

PS:employee is my DB name The column on A table is

id name ....
1  john
2  mary
3  susan

How can I select all column by the leftjoin? the column A.id is one to many relationship to the B.p_id column.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To fix this issue you need to specify required columns in select list and group by clause

$search_alls=DB::table('a16s as A')
                ->select('A.id','A.name')
                ->addSelect(DB::raw('SUM(CASE WHEN B.approve = 1 ELSE 0 END) as Yshow'))
                ->leftjoin('a16s_likes as B', function($join) {
                    $join->on('A.id', '=', 'B.p_id');
                })
                ->groupBy('A.id')
                ->groupBy('A.name');
    ->get();

As per newer release mysql 5.7 does not permit queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are not named in the GROUP BY clause

12.19.3 MySQL Handling of GROUP BY


As per docs

MySQL 5.7.5 and up implements detection of functional dependence. If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them. (Before 5.7.5, MySQL does not detect functional dependency and ONLY_FULL_GROUP_BY is not enabled by default


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...