Bellow SQL command runs perfectly :
select * from `product` group by `owner_name` order by `id` asc
When I translate above code in my Laravel project to get the same result :
Product::select('*')
->orderBy('id','asc')->groupBy('owner_name')
->get();
This laravel code returns me error that
SQLSTATE[42000]: Syntax error or access violation: 1055
'db1.product.id' isn't in GROUP BY (SQL: select * from product group
by owner_name order by id asc)
Problem is I have many duplicated records with slight differences on some of their columns. I need to get them by owner_name and only one time .
Edit your applications's database config file config/database.php
In mysql array, set strict => false to disable MySQL's strict mode
You have don't need to do 'select(*)', by default it will select all columns data.
Try this:
Product::orderBy('id','asc')->groupBy('owner_name')
->get();
And if you want to fetch selected column you can do like this:
Product::select(['column_1', 'column_2'])
->orderBy('id','asc')->groupBy('owner_name')
->get();
Related
So I'm using Laravel eloquents to access data from my database - it's very similar to other statements in my code which work fine, but for some reason this isn't working:
$data->leftjoin('val_keys', function($leftJoin) use (&$key_words)
{
$leftJoin->on('val_keys.val_id', '=', 'vals.id');
})->whereRaw(DB::raw(sprintf('(LOWER(val_keys.key) LIKE "%%%s%%")', strtolower($key_words))));
I keep getting the following error, which shows that there is a group statement that is somehow being added to my SQL query despite the fact that I'm not putting it there:
Integrity constraint violation: 1052 Column 'id' in group statement is ambiguous (SQL: select count(*) as aggregate from `vals` left join `val_keys` on `val_keys`.`val_id` = `vals`.`id` where (`category_id` = 3780) and (LOWER(val_keys.key) LIKE "%hey%") group by `id`)
I've tried adding my own groupBy() to my query, with vals.id as the input, hoping that this would override the group statement that uses id, but it doesn't:
Integrity constraint violation: 1052 Column 'id' in group statement is ambiguous (SQL: select count(*) as aggregate from `vals` left join `val_keys` on `val_keys`.`val_id` = `vals`.`id` where (`category_id` = 3780) and (LOWER(val_keys.key) LIKE "%hey%") group by `vals`.`id`, `id`)
How do I get rid of this group statement so my query will run as intended? I've already tried changing strict to true. I am using Laravel version 5.2.
Thanks
I want to perform a query like to get the last record of any type in DB, at my localhost, I use Maria Db and the query is as follow:
SELECT *
FROM table_a
WHERE column_a=999
OR column_b=999
GROUP
BY `group`;
group is a column which I save type in it, for instance: marketing, blog, order, etc
This query works fine on local, but on the server I get the following error:
SQLSTATE[42000]:
Syntax error or access violation:
1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column
'db_name.table_a.id' which is not functionally dependent on columns in GROUP BY clause;
this is incompatible with sql_mode=only_full_group_by\n
The SQL being executed was:
SELECT * FROM `table_a` WHERE (`column_a`=999) OR (`column_b`=999) GROUP BY `group`"
According to MySQL document I can use the following command to make this possible:
SET GLOBAL sql_mode=(SELECT REPLACE(##sql_mode,'ONLY_FULL_GROUP_BY',''));
But I don't have the sufficient privilege on Db and get the following error:
#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation
I asked the hosting to do this for me, they replied that they don't want to do this action
I use the YII2 framework, and now I want a way to add this on the option of database_config.php of the framework or change the query to something else with the same result, and not losing performance
ONLY_FULL_GROUP_BY is a good thing, which enforces basic ANSI SQL rules. Don't change it, fix your code instead.
From there one: you want entire records, so you should not think aggregation, but filtering.
Then: in a database table, records are unordered; for your question to just make sense, you need a column that defines the ordering of rows in each group, so it unambiguous what "last" record mean. Let me assume that you have such column, called id.
Here is a typical approach at this top-1-per-group problem, using a correlated subquery for filtering:
SELECT *
FROM table_a a
WHERE
999 IN (column_a, column_b)
AND id = (
SELECT MAX(a1.id)
FROM table_a a1
WHERE 999 IN (a1.column_a, a1.column_b) AND a1.grp = a.grp
)
Alternatively, if you are running MySQL 8.0, you can use window functions:
SELECT *
FROM (
SELECT a.*,
ROW_NUMBER() OVER(PARTITION BY grp ORDER BY id DESC) rn
FROM table_a a
WHERE 999 IN (column_a, column_b)
) a
WHERE rn = 1
Side note: group is a language keyword, hence a poor choice for a column name. I renamed it to grp in the queries.
There are a few ways to "bypass" the sql_mode but be aware that the result you get might not be correct.
First you can use ANY_VALUE(). Example like this:
SELECT any_value(column_a), any_value(column_b), `group` FROM table_a
WHERE (column_a=999) OR (column_b=999) GROUP BY `group`;
When using ANY_VALUE() function you have to write all the columns in SELECT from the table and append with ANY_VALUE() except for the column that you use in the GROUP BY.
Using MAX() or MIN() can return result but still it might not be the correct
result, especially for any row(s) that have more than 1 count:
SELECT MAX(column_a), MAX(column_b), `group`
FROM table_a
WHERE (column_a=999) OR (column_b=999) GROUP BY `group`;
Using GROUP_CONCAT will give you a view at what are the values in non-grouped columns. Compare the results with the other queries above and you can see on row(s) that returns more than one count, does the other queries returning according to what you want?
SELECT group_concat(column_a), group_concat(column_b), group_concat(`group`)
FROM table_a
WHERE (column_a=999) OR (column_b=999) GROUP BY `group`;
I'm not sure if you can do this but you can set the sql_mode off temporarily then you should be able to run your query:
SET sql_mode=""; -- you don't need to set global privilege.
SELECT * FROM table_a
WHERE (column_a=999) OR (column_b=999) GROUP BY `group`;
Demo here.
Still, the best option is to retain the sql_mode as it is and construct the query according to the requirement.
P/S: GROUP is a reserved word in both MySQL & MariaDB. You can use it as column name but you have to always add back-ticks to define the column or else, running the query will return you an error like
Query: select * from table_a group by group
Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'group' at line 1
i get this error when i upload it on online cpanel
Syntax error or access violation: 1055 Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'dreamsch_school_management.students.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select class, count(*) as total from students group by class order by id asc)
in controller i Used
$groups = DB::table('students')
->select('class', DB::raw('count(*) as total'))
->groupBy('class')
->orderBy('id', 'ASC')
->get();
i want to arrange in assending order by class. in bar chart. but it give error in order by line but correctly runs in my localhost. can you please help me with the query.
It was my expectation
but without ordering i get this one
Please see the labels in the pictures then you can get the errors. now I want to know how can I place ordering by ID or class when I upload my project in cpanel.
you have to disabled strict mode in your mysql server
just put 'strict' => false in your config/database in the server
This question already has answers here:
Group by not working - Laravel
(8 answers)
Closed 3 years ago.
I'm trying to use order by without adding the order column in groupby, it only works if I execute it directly from the database but from laravel I get database error
I made this eloquent code
Comment::select('product_id')->where('shop_name', $shop)->groupby('product_id')->distinct()->orderBy('created_at')->paginate(12)
it will product the following query
select distinct DISTINCT(product_id) from comments where shop_name
= 'shopname' group by product_id order by created_at asc limit 12 offset 0
if I rub the above query directly in database it works
but if I use Laravel eloquent code it fires this error
SQLSTATE[42000]: Syntax error or access violation: 1055
'areviews_areviewzappz.comments.created_at' isn't in GROUP BY (SQL:
select distinct DISTINCT(product_id) from comments where shop_name
= 'shopname' group by product_id order by created_at asc limit 12 offset 0)
how can I solve this issue ?
The issues is that you SHOULD really include the ORDER BY in the GROUP BY list as this is best practise.
The reason it works when you are on the the sql mode set to ''. However, Laravel by default (I think) has Strict as TRUE,
You have 2 options:
Add the created_at to the GROUP BY clause (Recommended)
Change the strict mode to false
A bit more info on the 2nd option:
How can I solve incompatible with sql_mode=only_full_group_by in laravel eloquent?
You can group it after you have retrieved the results rather than in the MySQL query - so you group the collection after it has been retrieved, not the table entries in the query itself.
Comment::select('product_id')
->where('shop_name', $shop)
->distinct()
->orderBy('created_at')
->paginate(12)
->groupBy('product_id')
Laravel collection groupBy method: https://laravel.com/docs/5.7/collections#method-groupby
Related post: Laravel Query Buider Group By Not Getting All The Records
\App\Service::groupBy('type')->orderBy('id', 'DESC')->get();
I am using laravel 5.5..
Can help me for resolve this problem..?
Error report
"SQLSTATE[42000]: Syntax error or access violation: 1055 'db_name.tbl_name.id' isn't in GROUP BY (SQL: select * from tbl_name group by type order by id desc) "
If you got this error
SQLSTATE[42000]: Syntax error or access violation: 1055 'tablename.fieldname' isn't in GROUP BY (SQL: select * from `tablename` group by `fieldname`)
Then edit your database config file config/database.php
In mysql array, set strict => false to disable MySQL's strict mode
When grouping in MySQL you can only work with either fields you are grouping by or fields used in aggregate functions of your select. Therefore orderBy('id', 'DESC') will do nothing in your case.