error in grouping by year,month in mysql - mysql

I have this code, and it is working properly on the online server:
SELECT
DATE(`order`.`date`) AS `dater`,
COUNT(*) AS `orders-amount`,
SUM(`order`.`price`) AS `orders-income`,
(SELECT SUM(`amount`) FROM `paypal` WHERE `paypal`.`txn_id` != 'Bonus' AND YEAR(`dater`) = YEAR(`paypal`.`posted_date`) AND MONTH(`dater`) = MONTH(`paypal`.`posted_date`)) AS `total_charge`
FROM `order`
GROUP BY YEAR(`dater`), MONTH(`dater`)
ORDER BY `dater` DESC
But on localhost it gives an error as below:
#1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'panel.order.date' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
Id I used this code for grouping then it working properly:
GROUP BY `dater`
This error appear only on localhost as I'm running on linux Mint and installing the apache, php, mysql & pypmyadmin

It means that different sql modes are used on local and remote servers.
Either you should change the mode or update your query like:
SELECT
YEAR(ANY_VALUE(`order`.`date`)) date_year,
MONTH(ANY_VALUE(`order`.`date`)) date_month,
COUNT(*) AS `orders-amount`,
SUM(`order`.`price`) AS `orders-income`,
(SELECT SUM(`amount`) FROM `paypal` WHERE `paypal`.`txn_id` != 'Bonus' AND YEAR(ANY_VALUE(`order`.`date`)) = YEAR(`paypal`.`posted_date`) AND MONTH(ANY_VALUE(`order`.`date`)) = MONTH(`paypal`.`posted_date`)) AS `total_charge`
FROM `order`
GROUP BY date_year, date_month

You have it in your error message:
this is incompatible with sql_mode=only_full_group_by
If you did not set it on purpose, I guess you got it by default and you have a different version on your local server (see here, it was made default at some point).
So all you need is to disable this mode, either by running SET sql_mode='';, or by following instructions here

Related

In aggregated query without GROUP BY, expression

My query is running well in local server but in live server its getting error.
my local Server version: 10.1.36-MariaDB - mariadb.org binary distribution
and live Server version: 5.7.25-cll-lve - MySQL Community Server - (GPL)
Error message:
In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'uzzal_management.employee.id'; this is incompatible with sql_mode=only_full_group_by
Query:
SELECT `employee`.*,
(SELECT `des_name` FROM `designation`
WHERE `employee`.`des_id` = `designation`.`id`) AS name,
(SELECT `dep_name` FROM `department`
WHERE `employee`.`dep_id` = `department`.`id`) AS dep_name,
`emp_salary`.`total`,
`bank_info`.*,
`addition`.*,
`deduction`.*,
(SELECT TRUNCATE((SUM(ABS(( TIME_TO_SEC( TIMEDIFF( `signin_time`, `signout_time` ) ) )))/3600), 1) AS Hours FROM `attendance`
WHERE (`attendance`.`emp_id`='Gup1410') AND (DATE_FORMAT(`attendance`.`atten_date`, '%m'))=MONTH(CURRENT_DATE())) AS hours_worked,COUNT(*) AS days FROM `employee`
LEFT JOIN `department` ON `employee`.`dep_id`=`department`.`id`
LEFT JOIN `addition` ON `employee`.`em_id`=`addition`.`salary_id`
LEFT JOIN `deduction` ON `employee`.`em_id`=`deduction`.`salary_id`
LEFT JOIN `bank_info` ON `employee`.`em_id`=`bank_info`.`em_id`
LEFT JOIN `emp_salary` ON `employee`.`em_id`=`emp_salary`.`emp_id`
WHERE `employee`.`em_id`='Gup1410'
go to variable and check for sql_mode there you will find out ONLY_FULL_GROUP_BY, remove it and save it. it will work.

Rewrite the SQL in version 5.7

I have a following SQL which works in mysql version 5.6 but is breaking in mysql version 5.7.x.
SELECT * FROM (SELECT * FROM photos WHERE photoable_type = 'Mobilehome'
AND photoable_id IN (SELECT id FROM mobilehomes WHERE
mobilehomes.community_id = 1) AND photos.image_file_size IS NOT NULL
AND photos.is_published IS TRUE ORDER BY photos.priority ASC) AS tmp_table
GROUP BY photoable_id
It's throwing me following error:
Expression #1 of SELECT list is not in GROUP BY clause and contains
nonaggregated column 'tmp_table.id' which is not functionally
dependent on columns in GROUP BY clause; this is
incompatible with sql_mode=only_full_group_by
In this case or you change the sql mode for instrcut the db to work as mysql 5.6 version or you can adeguate your query to the new behavior
In this second case
If you use group by whithout aggregation function this mean that for all the column different from photoable_id you accept casual result
This mean that you could, probably, also accepted an aggregated result based greagtion function eg: on min() or max ()
assuming your tables containg col1, col2, .. the you must declare explicitally the column you need
SELECT photos.photoable_id, min(col1), min(col2),....
FROM photos
INNER JOIN mobilehomes ON mobilehomes.community_id = 1
AND photos.photoable_type = 'Mobilehome'
AND photos.photoable_id = mobilehomes.id
AND photos.image_file_size IS NOT NULL
AND photos.is_published IS TRUE
GROUP BY photos.photoable_id
ORDER BY photos.priority ASC
Looking to your code seems also that you could avoid the subquery

mysql error "ERROR 3029 (HY000): Expression #1 of ORDER BY contains aggregate function and applies to the result of a non-aggregated query"

I am executing the below query
SELECT DISTINCT n.nid AS entity_id
FROM node n
INNER JOIN og_membership om ON n.nid=om.etid AND om.entity_type='node'
INNER JOIN foster_animal_capacity fc ON n.nid=fc.person_id
LEFT OUTER JOIN field_data_field_attributes fa ON n.nid=fa.entity_id
LEFT OUTER JOIN foster_person_black_outs fb ON n.nid=fb.person_id
WHERE -- n.nid = 1441663 AND
(om.gid = 464) AND (fc.animal_type_id = 3)
AND ((fc.capacity - fc.occupied)>=1)
AND ((fb.start_date IS NULL) OR (fb.end_date < 1523577600) OR (fb.start_date > 1522540800))
AND ((SELECT pid FROM `animal_history` WHERE `TYPE` = 'Foster Return'
AND pid = n.nid ORDER BY DATE_FORMAT(FROM_UNIXTIME( UNIX_TIMESTAMP( ) - MAX( CAST(`time` AS UNSIGNED) ) ) ,'%e')));
The query executing perfectly in MySql 5.5.5
But showing the below error in MySql 5.7.21
ERROR 3029 (HY000): Expression #1 of ORDER BY contains aggregate function and applies to the result of a non-aggregated query
Why is this happening? And how can I overcome this issue?
I am not able to find any documentation for the error code 3029
As mentioned in MySQL documention :
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. For a description of pre-5.7.5 behavior, see the MySQL 5.6
For detail please check:
MySQL Handling of GROUP BY

GROUP BY invalid when upgraded MySQL version

When I upgraded my ubuntu from 15.10 to 16.04 I have this error in my yii project:
CDbCommand failed to execute the SQL statement: SQLSTATE[42000]:
Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column
'v4master.A.id' which is not functionally dependent on columns in
GROUP BY clause; this is incompatible with
sql_mode=only_full_group_by. The SQL statement executed was:
The sql code is follows:
$sql = "SELECT A.*,B.`type_name` FROM `".$this->tbl_auth_user_items."` A
INNER JOIN `".$this->tbl_auth_context_types."` B ON A.`type_id` = B.`type_id`
WHERE A.`user_id` = '".$user_id."' GROUP BY A.`type_id`, A.`type_value` ORDER BY A.`type_id` DESC";
return $this->_db->createCommand($sql)->queryAll();
Run this query at Mysql;
set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
Coild that your upgrade implies also a db upgrade to mysql 5.7 if so you must know that
starting for mysql 5.7 the use of column in select without aggreation function and not mentioned in group by is not allowed by default
if you need distinct result set ypu should use distinct clause and not group by
$sql = "SELECT DISTINCT
A.*,B.`type_name`
FROM `".$this->tbl_auth_user_items."` A
INNER JOIN `".$this->tbl_auth_context_types."` B ON A.`type_id` = B.`type_id`
WHERE A.`user_id` = '".$user_id."'
ORDER BY A.`type_id` DESC";
return $this->_db->createCommand($sql)->queryAll();
or ( but is deprecated) you can change the sql_mode for reverting to the previuos version behavior
fro
sql_mode = 'ONLY_FULL_GROUP_BY';
to
SET sql_mode = ''

MySQL query with distinct and order by showing error 3065(HY000)

I am using linux mint in my machine and trying to execute a query. After the execution, an error is displayed
ERROR 3065 (HY000): Expression #1 of ORDER BY clause is not in SELECT list, references column 'shelterl_local.animal.changed' which is not in SELECT list; this is incompatible with DISTINCT
I added line
[mysqld]
sql-mode=''
in /etc/mysql/my.cnf file and restarted mysql. But still getting the same error. I referred many solutions but nothing worked for me. My query is
SELECT DISTINCT fs.etid AS etid FROM og_membership fs
LEFT OUTER JOIN node animal ON animal.nid = fs.etid LEFT OUTER JOIN
field_data_field_for_animal dfa ON dfa.field_for_animal_value = fs.etid
LEFT OUTER JOIN node pastid ON pastid.nid = dfa.entity_id WHERE ( (fs.gid =
464) OR
(animal.nid IN
(1196113,1211208,1218831,1243640,1254254,
1253603,1249890,1261729,1261282,1258378,1273745,1270760,
1279219,1276040,1276031,1275684,1288727,1289306,1300545,
1313770,1313761,1313755,1313746,1313330,1312388,1310673,
1309431,1315024,1333640,1328041,1323565,1327216,1330104,
1327786,1326810,1335812,1333094,1341309,1340358,1348088,
1351077,1351071,318214,1342698,1472755,1491527,1351652,1353488,
1507763,1342713)) )AND (fs.entity_type = 'node')
AND (animal.type = 'animal') AND (animal.status = 1) AND (pastid.title LIKE
'%A%')
ORDER BY animal.changed DESC LIMIT 0,300;
Is it possible to remove this error permanently and execute the query? Please help
Your initial query is equivalent to the following:
SELECT field1 AS f1
FROM table t
--Joins and conditions
GROUP BY field1
ORDER BY field2 DESC LIMIT 0,300
This can't make logical sense, because each value of field1 in the result set may have multiple values of field2 associated with it. The error you are seeing is MySQL's way of saying it can't figure out what you want to do. One workaround would be to sort on an aggregate of field2, e.g. try the following:
SELECT field1 AS f1
FROM table t
--Joins and conditions
GROUP BY field1
ORDER BY MAX(field2) DESC -- or AVG(field2), or MIN(field2), etc.
LIMIT 0,300
You need to actually select field2
SELECT DISTINCT field1 AS f1,
field2
FROM table t
--Joins and conditions
ORDER BY field2 DESC LIMIT 0,300
UPDATE:
I know sometimes theres errors when using DISTINCT and ORDER BY in the same query. To fix this i would give the animal.changed section an ALIAS such as [animal.changed] and then if you ORDER BY [animal.changed] this should not error. At least i know this definitely works in SQL server
E.G
SELECT DISTINCT animal.changed AS [animal.changed]
FROM .....
ORDER BY [animal.changed]
This is very basic but would allow you to use DISTINCT and ORDER BY in the same query which is the current error you're getting.
If you select a column then sorting can only be done for this column. If you need to sort by another column, then necessarily include this column in the selection.
//wrong.....
$sql="Select DISTINCT Rubrika from tmp3 order by View desc limit 3";
$res_r=mysqli_query($Link, $sql);
//RIGHT!!!
$sql="Select DISTINCT Rubrika, View from tmp3 order by View desc limit 3";
$res_r=mysqli_query($Link, $sql);
I also encountered the same issue and abled to resolve it. Since I'm using Windows I'll post fix for windows but similar fix will work for linux as well.
This is happening because ONLY_FULL_GROUP_BY mode is enabled by mysql. You can disable this by modifying my.ini file. (In linux this would be my.cnf).
Open my.ini file.
This file might be located in a hidden directory ProgramData.
C:\ProgramData\MySQL\MySQL Server 8.0
Find following config which is placed under [mysqld] section.
sql-mode="ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"
Remove ONLY_FULL_GROUP_BY from here
sql-mode="STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"
Restart mysql server
net stop MYSQL80
net start MYSQL80