首先,這個異常是數據SQL語法異常
先上異常截圖:
{"msg":"服務器出現未知錯誤,請聯繫管理員!","data":"org.springframework.jdbc.BadSqlGrammarException:
\n### Error querying database. Cause:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
Expression
#1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'cmis.sys_clock_in.id_' which is not functionally dependent on columns in GROUP BY clause;
this is incompatible with sql_mode=only_full_group_by\n###
The error may exist in class path resource [mybatis/SysClockInMapper.xml]\n### The error may involve com.sinosoft.sys.mapper.SysClockInMapper.getMonitorList-Inline\n###
The error occurred while setting parameters\n### SQL:
select count(0) from (select id_ as 'id', user_id_ as 'userId', user_name_ as 'userName', org_id_ as 'orgId', org_name_ as 'orgName', clock_time_ as 'clockTime', clock_type_ as 'clockType' from sys_clock_in where TO_DAYS( clock_time_ ) = TO_DAYS( NOW( ) ) GROUP BY user_id_,org_id_ HAVING count( user_id_ ) = 1) tmp_count
\n### Cause:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
Expression
#1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'cmis.sys_clock_in.id_' which is not functionally dependent on columns in GROUP BY clause;
this is incompatible with sql_mode=only_full_group_by
; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
Expression
#1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'cmis.sys_clock_in.id_' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by\n\tat org.springframework.jdbc.support.SQLExceptionSubclassTranslator.doTranslate(SQLExceptionSubclassTranslator.java:93)\n\tat org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)\n\tat org.springframework.jdbc.support.AbstractFallbackSQLException
出現這個異常是以爲今天同事提出的, 本地執行SQL沒有問題,但是在線上就報錯,查了mysql版本都是5.7的.
sql語句如下
SELECT
count( 0 )
FROM
(
SELECT
id_ AS 'id',
user_id_ AS 'userId',
user_name_ AS 'userName',
org_id_ AS 'orgId',
org_name_ AS 'orgName',
clock_time_ AS 'clockTime',
clock_type_ AS 'clockType'
FROM
sys_clock_in
WHERE
TO_DAYS( clock_time_ ) = TO_DAYS( NOW( ) )
GROUP BY
user_id_,
org_id_
HAVING
count( user_id_ ) = 1
) tmp_count
經過漫長的排查後發現在MySQL的5.7.5之後有個設置是ONLY_FULL_GROUP_BY默認是開啓狀態.
默認的sql-mode裏的ONLY_FULL_GROUP_BY字段導致不能直接查詢group_by包裹的之外的字段.
類似上面的語句聚合函數默認的參數是主鍵column, 這裏是id_. 只需要在group by 後添加參數id_ 就行了
SELECT
count( 0 )
FROM
(
SELECT
id_ AS 'id',
user_id_ AS 'userId',
user_name_ AS 'userName',
org_id_ AS 'orgId',
org_name_ AS 'orgName',
clock_time_ AS 'clockTime',
clock_type_ AS 'clockType'
FROM
sys_clock_in
WHERE
TO_DAYS( clock_time_ ) = TO_DAYS( NOW( ) )
GROUP BY
<!-- 在此處添加主鍵字段 -->
id_,
user_id_,
org_id_
HAVING
count( user_id_ ) = 1
) tmp_count