Skip to content

Latest commit

ย 

History

History
81 lines (53 loc) ยท 2.65 KB

2023-06-07-only_full_group_by-mysql.md

File metadata and controls

81 lines (53 loc) ยท 2.65 KB

only_full_group_by ๋ชจ๋“œ - MySQL ํŠธ๋Ÿฌ๋ธ”์ŠˆํŒ…

๊ธฐ๋ณธ ํ™˜๊ฒฝ: docker image mysql:latest

๋ฌธ์ œ

์•„๋ž˜์™€ ๊ฐ™์€ ์ฟผ๋ฆฌ๋ฌธ ์‹คํ–‰

SELECT cs.clientId, cs.clientName, cg.groupId, g.groupName
    FROM Clients AS cs
    LEFT OUTER JOIN ClientGroups cg ON cs.clientId = cg.clientId
    LEFT OUTER JOIN `Groups` g ON g.groupId = cg.groupId GROUP BY cs.clientId

์—๋Ÿฌ ๋ฉ”์‹œ์ง€ ๋ฐœ์ƒ

[42000][1055] Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sendingo_test.cg.groupId' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

์‹œ๋„ ๋ฐ ํ•ด๊ฒฐ

sql_mode ์กฐํšŒ

SELECT @@sql_mode;

SELECT @@session.sql_mode;

-- ๊ธฐ๋ณธ : ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION

sql_mode ๋ณ€๊ฒฝ

  • ONLY_FULL_GROUP_BY ์ œ์™ธํ•œ ๊ฐ’์œผ๋กœ ์„ค์ •
-- ๋ชจ๋“  ์„ค์ • ์ดˆ๊ธฐํ™”
SET GLOBAL sql_mode ='';
SET SESSION sql_mode = '';

-- ONLY_FULL_GROUP_BY ๋ฅผ ์ œ์™ธํ•˜๊ณ  ์„ค์ •
SET SESSION sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';

์•Œ๊ฒŒ ๋œ ์ 

SQL only_full_group_by ๋ชจ๋“œ

  • MySQL์—์„œ ์‚ฌ์šฉ๋˜๋Š” SQL_MODE
  • GROUP BY ์ ˆ์—์„œ ์„ ํƒ๋˜์ง€ ์•Š์€ ์ปฌ๋Ÿผ์ด๋‚˜ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ ๋ฐœ์ƒํ•˜๋Š” ์—๋Ÿฌ๋ฅผ ๋ฐฉ์ง€ํ•จ

๋งŒ์•ฝ only_full_group_by ๋ชจ๋“œ๊ฐ€ ์„ค์ •๋˜์–ด ์žˆ์ง€ ์•Š์œผ๋ฉด, ์œ„์—์„œ ๋งํ•œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š์Œ. ํ•˜์ง€๋งŒ ํ•ด๋‹น ๋ชจ๋“œ๋ฅผ ํ•ด์ œํ•˜๋ฉด ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ ์ž˜๋ชป๋œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, ๋ฐ์ดํ„ฐ ์ผ๊ด€์„ฑ์— ๋ฌธ์ œ๊ฐ€ ์ƒ๊ธธ ์ˆ˜ ์žˆ์Œ.

์˜ˆ์‹œ:

SELECT column1, column2, AVG(column3)
FROM table1
GROUP BY column1

์œ„ SQL ์ฟผ๋ฆฌ์—์„œ column2๋Š” GROUP BY ์ ˆ์— ๋„ฃ์ง€ ์•Š์€ ์ปฌ๋Ÿผ

only_full_group_by ๋ชจ๋“œ๊ฐ€ ์„ค์ •๋˜์–ด ์žˆ์ง€ ์•Š์€ ๊ฒฝ์šฐ, ๋ฌธ์ œ ์—†์ด ์‹คํ–‰๋˜๋‚˜ column2๋Š” column1 ๋ณ„๋กœ ๋‹ค๋ฅธ ๊ฐ’์„ ๊ฐ€์งˆ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ, ๊ฒฐ๊ณผ๊ฐ€ ๋ถˆ์ผ์น˜ํ•  ๊ฐ€๋Šฅ์„ฑ์ด ๋†’์Œ

๋”ฐ๋ผ์„œ, only_full_group_by ๋ชจ๋“œ๋Š” ๋ฐ์ดํ„ฐ ์ผ๊ด€์„ฑ์„ ์œ ์ง€ํ•˜๊ธฐ ์œ„ํ•ด ๊ผญ ์„ค์ •ํ•ด์ฃผ๋Š” ๊ฒƒ์ด ์ข‹์Œ.

์„ค์ • ๋ฐฉ๋ฒ•:

SET GLOBAL sql_mode=(SELECT CONCAT(@@sql_mode, ',ONLY_FULL_GROUP_BY'));

์ฐธ๊ณ ์ž๋ฃŒ