简体   繁体   中英

SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')) for Jpa Repository

I'm trying to use a custom query like this:

@Query("SELECT i " + 
       "FROM ManagerWorkplace i " + 
       "WHERE i.managerId = ?1 " + 
       "AND i.companyId = ?2 " + 
       "GROUP BY i.zoneId")
List<ManagerWorkplace> findByManagerIdAndCompanyId(Long managerID, Long companyId);

but I got this error:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'db_oem.managerwor0_.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

I know a way to fix this error on MySQL by using

SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''))

, is there any way to do the same for JpaRepository?

Your query is not okay. You are selecting columns which are not in the result table of the group by. It has nothing to do with Java or JPA.

With a group by you are creating a new table. There will be one row for every zoneId. Suppose in the original table there are multiple rows with a certain zoneId, and for at least one column there are different values in those rows. Which one should it take in the new table? This cannot be done.

You can also group by multiple columns. In the new table there will be one row for every combination of those columns.

So in the new table you can select for the columns which are in the group by, in your case zoneId. What other things you can put in the new table? For example how many values of a column there are for a zoneId. This can be done. Or the maximum or minimum of a column (remember which has multiple values). This can also be done. This are the aggregates where they were talking about.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM