Syntax error or access violation 1055

I want to use WhereIn and Groupby in the same query to fetch Result. I've tried this: $loadids=explode("#@*",$reciptdet->loading_id); $loadingdatas=DB::table('loading')->groupBy('

I want to use WhereIn and Groupby in the same query to fetch Result.

I’ve tried this:

$loadids=explode("#@*",$reciptdet->loading_id);
$loadingdatas=DB::table('loading')->groupBy('vehicle_no')->whereIn('id',$loadids)->get();

But I got this error message:

SQLSTATE[42000]: Syntax error or access violation: 1055 ‘sbrtpt.loading.id’ isn’t in GROUP BY (SQL: select * from loading where id in (14, 15, 16) group by vehicle_no)

asked Dec 1, 2016 at 17:48

Karthikvijayaveni's user avatar

5

Short answer

In configdatabase.php —> "mysql" array

Set 'strict' => false to disable all.

…. or

You can leave 'strict' => true and add modes to "mysql" option in

'mysql' => [
       ...
       ....
       'strict' => true,
       'modes' => [
            //'ONLY_FULL_GROUP_BY', // Disable this to allow grouping by one column
            'STRICT_TRANS_TABLES',
            'NO_ZERO_IN_DATE',
            'NO_ZERO_DATE',
            'ERROR_FOR_DIVISION_BY_ZERO',
            'NO_AUTO_CREATE_USER',
            'NO_ENGINE_SUBSTITUTION'
        ],
 ]

Detailed answer

You may not need to disable all strict options …
Kindly have a look on this answer about this issue.

answered Jul 8, 2017 at 10:03

Husam's user avatar

9

This is probably a SQL_MODE problem. In your config/database.php, in the connection, change

strict => false

As in

'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', 'localhost'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix' => '',
    'strict' => false,
    'engine' => null,
],

answered Dec 1, 2016 at 19:15

Antonio Carlos Ribeiro's user avatar

3

No need to change any where in your System jut use code like in laravel

DB::statement("SET SQL_MODE=''");//this is the trick use it just before your query

$data=Task::where('user_id', Auth::user()->id)->where('status', 0)->groupBy('task_code')->get(['id','task_code', 'title']);

answered Feb 16, 2021 at 12:30

Sk Bindas's user avatar

Sk BindasSk Bindas

5796 silver badges4 bronze badges

5

Without modifiying configdatabase.php file

Set 'strict' => false in the configdatabase.php could be a security issue. So, a simple Laravel solution could be first call get() and then groupBy('vehicle_no):

$loadids = explode("#@*", $reciptdet->loading_id);
$loadingdatas = DB::table('loading')->whereIn('id', $loadids)->get();
$grouped = $loadingdatas->groupBy('vehicle_no');

answered Feb 18, 2019 at 1:12

cespon's user avatar

cesponcespon

5,5107 gold badges31 silver badges45 bronze badges

3

You can leave 'strict' => true and add modes to «mysql» option in.

'mysql' => [
   ...
   ....
   'strict' => true,
   'modes' => [
        //'ONLY_FULL_GROUP_BY', // Disable this to allow grouping by one column
        'STRICT_TRANS_TABLES',
        'NO_ZERO_IN_DATE',
        'NO_ZERO_DATE',
        'ERROR_FOR_DIVISION_BY_ZERO',
        // 'NO_AUTO_CREATE_USER', // This has been deprecated and will throw an error in mysql v8

        'NO_ENGINE_SUBSTITUTION'
    ],
 ]

Sven Eberth's user avatar

Sven Eberth

3,02712 gold badges23 silver badges28 bronze badges

answered Jun 12, 2021 at 1:26

Christopher C Okonkwo's user avatar

1

update config/database.php

set:

'mysql' => [
     'strict' => false,
],

instead of:

'mysql' => [
     'strict' => true,
],

and don’t forget to clear cache:

php artisan config:cache

Osanda Gamage's user avatar

answered Mar 16, 2020 at 10:46

Gouda Elalfy's user avatar

Gouda ElalfyGouda Elalfy

6,7481 gold badge25 silver badges37 bronze badges

1

I was having this problem also but after changing 'strict' => true, to 'strict' => false, the error disappeared.

You can find this setting in:

configdatabase.php

'mysql' => [
    ...
    'strict' => false,
    ...
]

Chuck Le Butt's user avatar

Chuck Le Butt

46.9k61 gold badges197 silver badges286 bronze badges

answered Jun 6, 2018 at 12:55

Zakhele's user avatar

ZakheleZakhele

971 silver badge2 bronze badges

1

Whenever using groupBy in eloquent, always include the column name used in the groupBy function in the select() function.

$loadids=explode("#@*",$reciptdet->loading_id);
$loadingdatas=DB::table('loading')->select('vehicle_no')->groupBy('vehicle_no')->whereIn('id',$loadids)->get();//add select('vehicle_no')

Also it is a bad practice to disable strict mode in the config file. Doing so may cause corrupt data to enter the database such as invalid dates without any warnings.Don’t do that unless absolutely necessary.

answered Jun 21, 2018 at 8:23

Thungdemo's user avatar

ThungdemoThungdemo

1272 silver badges5 bronze badges

1

SQLSTATE[42000]: Syntax error or access violation: 1055  in GROUP BY

If you get the above error, add the following into your database.php file in the config folder:

'mysql' => [
    'strict' => true,
    'modes' => [
        'STRICT_TRANS_TABLES',
        'NO_ZERO_IN_DATE',
        'NO_ZERO_DATE',
        'ERROR_FOR_DIVISION_BY_ZERO',
        'NO_AUTO_CREATE_USER',
        'NO_ENGINE_SUBSTITUTION'
    ],
]

Jakye's user avatar

Jakye

6,2913 gold badges17 silver badges36 bronze badges

answered Aug 6, 2021 at 9:18

Fredrick Kiprop's user avatar

This restriction makes sense as when you use GROUP BY in MySQL, it returns one row for each value in the columns used in GROUP BY. So, the values of other columns in the selected rows do not make sense to use anywhere. So, it’s always recommended to use the best practice and I would recommend not to disable MySQL Strict Mode.

Often developers may need rows of a query grouped by the value of a column. Here they don’t need only one row per the unique values of the columns. But they need multiple rows grouped by the unique values of a particular column. For some reason, they use groupBy Query Builder method of Laravel which generates a MySQL GROUP BY query and the developers encounter the above error.

The solution to their problem is to use groupBy Collection method instead. For example,

$loadingData = DB::table('loading')
    ->whereIn('id', $loadIds)
    ->get()
    ->groupBy('vehicle_no');

This will give them the desired result.

answered Jan 10, 2020 at 8:06

Debiprasad's user avatar

DebiprasadDebiprasad

5,65716 gold badges66 silver badges94 bronze badges

7

You might as well use:

distinct(‘vehicle_no’)

instead of groupBy(‘vehicle_no’) each case scenario is different, but looking at your query, distinct might be the way to go since you’re not aggregating data.

answered Jul 1, 2020 at 11:54

ben.c's user avatar

ben.cben.c

311 bronze badge

This is on laravel doc 8.x , it works well

 $users = DB::table('users')
             ->select(DB::raw('count(*) as user_count, status'))
             ->where('status', '<>', 1)
             ->groupBy('status')
             ->get();

answered May 14, 2021 at 15:27

Rachid Loukili's user avatar

add Schema::defaultStringLength(191); to boot method

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
         Schema::defaultStringLength(191);
    }
}

answered Mar 16, 2020 at 14:40

hamed hossani's user avatar

hamed hossanihamed hossani

9761 gold badge14 silver badges32 bronze badges

I solve a similar issue with using group by by first getting the columns i needed to sort then use the group by.

$SampleData= DB::table('tableExampleName')->get(['col1','col2'])->groupBy('col3');

then you can dd() the values and check if they are the right grouping. You can all assign it and pass it into your view for further testing.

Note: This is using Laravel 8.

answered Feb 23, 2022 at 19:33

ZackAttack's user avatar

1

Learn how to solve the MySQL error 1055 caused by the usage of the sql mode only_full_group_by.

A couple of weeks ago working in a legacy project that needed to be upgraded and moved to a new server got me in the next exception in a couple of modules of the application:

Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by.

According to the MySQL documentation, having the only full group by mode in the sql mode will reject 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 (uniquely determined by) GROUP BY columns.

In some cases, as the standard query won’t work with a default configuration in the mysql client, you may like as a good practice to rewrite it in a way that the exception doesn’t appear anymore, however due to time and costs of development, you will need a faster and not so expensive solution. The point of this solution is that the query worked in an older version of MySQL with different settings, so you may run the same queries by simply changing the sql mode of your MySQL client and we’ll show you how to do it in this short article.

1. Locate MySQL my.cnf file

The first thing that you need to do is to find the configuration file of MySQL. For example with many distribution as Plesk, you can find the file at /etc/mysql/my.cnf or at /etc/my.cfn, however this may vary, so you will be able to find it using a linux command like:

find / -name my.cnf

This will output the path to the files with such name. Once you find the file, you will be able to change the setting that will remove the exception from appearing.

2. Modify sql mode

Inside the [mysqld] setting block you need to update the value of the sql_mode property to an empty string which will remove the 'only_full_group_by' mode:

# Inside the mysqld block
[mysqld]
# add new option
sql_mode = ""

Edit the my.cnf file using either nano, vi, emacs or via SFTP and save the changes. For example, the my.cnf file would end up like this with our new setting:

#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

#
# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#

!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/
[mysqld]
sql_mode=ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
bind-address = ::ffff:127.0.0.1
local-infile=0

# Important: remove limitation of group by with the following line
sql_mode = ""

Save changes in the file and restart mysql with the cli depending of your os and installation process e.g:

# Ubuntu
sudo service mysql restart

# CentOS
/etc/init.d/mysqld start

Now the queries with the issue should be able to run now and the exception won’t appear anymore.

Happy coding !

Laravel 5 — «syntax error or access violation 1055 in group by» Solved

September 5, 2020
Category : Laravel

Yesterday i was working on my Laravel 5.4 application and when i use group by statement in query builder I found error like as bellow:

SQLSTATE[42000]: Syntax error or access violation: 1055 ‘admin.products.name’ isn’t in GROUP BY (SQL: select `products`.*, SUM(products_stock.stock) from `products` inner join `products_stock` on `products_stock`.`product_id` = `products`.`id` group by `products`.`id`)

I was thinking what will be error and why it comes. i thought maybe it comes from mysql. i just add following query using laravel builder as like bellow:

Laravel Query

$data = DB::table("products")

->select("products.*",DB::raw("SUM(products_stock.stock)"))

->join("products_stock","products_stock.product_id","=","products.id")

->groupBy("products.id")

->get();

But it’s give me error as i add bellow. I searched on google and finally i found solution. You have to open batabase.php configuration file and we have to just «strict» equal to false. So do it like as bellow:

config/database.php

<?php

return [

.....

'connections' => [

......

'mysql'[

.....

'strict' => false,

.....

]

]

]

I hope it can help you…

Hardik Savani

I’m a full-stack developer, entrepreneur and owner of Aatman Infotech. I
live in India and I love to
write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery,
Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.

Follow Me:

Popular Posts

  • How to Create Custom Error Page in Laravel 9?
  • Laravel tokenmismatchexception in verifycsrftoken.php — Solved
  • Laravel 5 create Custom Validation Rule example.
  • How to Send Email with Attachment in Laravel?
  • Laravel Multi Select Dropdown with Checkbox Example
  • Laravel Collection first() and firstWhere() Methods Example
  • Laravel 5.3 — import export csv and excel file into database
  • Laravel 5.2 and AngularJS CRUD with Search and Pagination Example.
  • Laravel Login and Registration using Ajax Tutorial
  • Laravel Inertia JS Pagination Example
  • How to Add Delete Cascade to Existing Column in Laravel?

Categories

  • Laravel
  • Angular
  • PHP
  • jQuery
  • Python
  • Bootstrap
  • Javascript
  • MySql
  • Ajax
  • Ubuntu
  • Node JS
  • HTML
  • Codeigniter
  • Guest Post
  • Vue.JS
  • React JS
  • Git
  • Server
  • Installation
  • JSON
  • CSS
  • .htaccess
  • Google Map
  • SQL
  • JQuery UI
  • Google API
  • Typeahead JS
  • Axios
  • Socket.io
  • Highcharts

Latest Posts

  • Ubuntu PHP bz2 Extension Install Commands Example
  • Ubuntu PHP bcmath Extension Install Commands Example
  • Ubuntu PHP ZIP Extension Install Commands Example
  • How to Install PHP XML Extension in Ubuntu?
  • How to Install PHP GD Extension in Ubuntu?

Понравилась статья? Поделить с друзьями:
  • Syntax error on tokens delete these tokens
  • Syntax error on token void record expected
  • Syntax error on token s misplaced construct s java
  • Syntax error on token println identifier expected after this token
  • Syntax error on token package import expected