JaeWon's Devlog
article thumbnail
Published 2022. 12. 17. 10:08
[ERROR] ONLY_FULL_GROUP_BY(Feat. MySQL) Error
반응형

로컬 환경에서 MySQL 로 GROUP BY 를 하려고 하면 아래 에러가 발생하였다.

select 
	department_id, admission_year, count(1) as cnt
from student_table
group by department_id, admission_year
;
Expression
#1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'department_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

쿼리만 본다면 잘못된 쿼리는 아닌 정상적인데 조회가 되지 않았다.

구글링을 해보니 MySQL 5.7 버전부터 sql_mode 라는 것이 생기게 되었고, 그중 only_full_group_by 가 선언되어 있어 발생한 문제였다.


1. 원인

- MySQL 이 5.7 버전으로 업그레이드 또는 설치를 하게 되면서 이전에는 없던 sql_mode 라는 기능으로 인해 기본적으로 설정되는 only_full_group_by 가 선언이 되면서 쿼리가 실패하였다.

- 해당 내용은 아래 공식 사이트를 통해서도 확인할 수 있다.

 

MySQL :: MySQL 5.7 Reference Manual :: 12.20.3 MySQL Handling of GROUP BY

12.20.3 MySQL Handling of GROUP BY SQL-92 and earlier does not permit queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are not named in the GROUP BY clause. For example, this query is illegal in sta

dev.mysql.com

2. 해결 방법

- 기본적으로 로컬 환경의 MySQL 의 sql_mode 를 조회한다.

# sql_mode 확인 Query
SELECT @@sql_mode;

2-1. 현재 연결된 Session(세션) 제거

- 간단하게는 쿼리를 수행시켜 sql_mode 항목을 변경하여 only_full_group_by 를 제거한다.

# 현재 연결된 Session 설정
set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';

# 전체 설정
set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';

2-2. 영구적 제거

- MySQL 서버를 시작/재시작 할 때마다 제거하기 위해서는 설정 파일(my.cnf)을 수정하여 재기동한다.

# 영구적 제거(파일 위치는 설치 위치에 따라 다를 수 있습니다.)
$ vi /etc/my.cnf


# 아래 내용 추가
...
[mysqld]
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
...

참고

- https://velog.io/@heumheum2/ONLYFULLGROUPBY

- https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html 

- https://info-lab.tistory.com/274

반응형
profile

JaeWon's Devlog

@Wonol

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!