SQL
MySQL / Error Code: 1055. Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column '컬럼명' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
JM_H
2023. 2. 4. 13:26
MySQL에서 GROUP BY 로 한 컬럼을 기준으로
오름차순으로 정렬하고 중복제거 후 하나의 row를 조회하려고 하는데
다음과 같이 error가 발생할 수 있는데,

Error Code: 1055. Expression #2 of SELECT list is not in GROUP BY clause and
contains nonaggregated column '컬럼명' which is not functionally
dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
SELECT
update_flag,
update_detail,
create_date
FROM
BOARD_RECORD
WHERE
board_idx = #{boardIdx}
GROUP BY
update_flag
HAVING
update_flag = 'A'
sql_mode 옵션 중 only_full_group_by 를 비활성화 하거나
그룹바이 절에 조회할 컬럼들을 전부 넣거나 그룹바이 절에 넣은 컬럼만 조회하면 되지만
위의 기존 쿼리문을 그대로 유지하고 그룹바이 절에 넣은 컬럼을 기준으로
오름차순 정렬 및 중복제거 후 조회하고 싶을 때는
나머지 컬럼들을 ANY_VALUE() 로 감싸주면 해결.
SELECT
update_flag,
ANY_VALUE(update_detail) AS update_detail,
ANY_VALUE(create_date) AS create_date
FROM
BOARD_RECORD
WHERE
board_idx = #{boardIdx}
GROUP BY
update_flag
HAVING
update_flag = 'A'