[MySQL] GROUP_CONCAT ์‚ฌ์šฉํ•˜๊ธฐ

SCYยท2023๋…„ 7์›” 26์ผ
0
post-thumbnail

๐ŸŽ ํ•„์š”์„ฑ

Pwith ํ”„๋กœ์ ํŠธ๋ฅผ ์ง„ํ–‰ํ•˜๋ฉด์„œ ์„ค๊ณ„ํ•œ ํ…Œ์ด๋ธ” ์ค‘
portfolio๋Š” ํฌํŠธํด๋ฆฌ์˜ค(๋ฉ˜ํ†  ์ž์†Œ์„œ)์— ๋Œ€ํ•œ ์ •๋ณด,
portfolioSubject๋Š” ํ•ด๋‹น ํฌํŠธํด๋ฆฌ์˜ค์˜ ๊ณผ๋ชฉ์„ ๋‹ด๊ธฐ ์œ„ํ•œ ํ…Œ์ด๋ธ”์ด๋‹ค.

portfolio

portfolioSubject









๋ฆฌํŒฉํ† ๋ง์„ ์ง„ํ–‰ํ•˜๊ธฐ ์ „ ์šฐ๋ฆฌ๋Š” portfolio ํ…Œ์ด๋ธ”์— subject ์ปฌ๋Ÿผ์„ varchar() ํƒ€์ž…์œผ๋กœ ์„ค์ •ํ•˜๊ณ  ๋ฌธ์ž์—ด์˜ ํ˜•์‹์œผ๋กœ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ €์žฅํ–ˆ๋‹ค. 1NF์˜ ์›์ž์„ฑ ์กฐ์ฐจ ๋งŒ์กฑํ•˜์ง€ ๋ชปํ–ˆ๋˜ ๋ฐฉ์‹์ด์—ˆ๋‹ค. ์—ฌ๋ฆ„๋ฐฉํ•™์„ ๊ฑฐ์ณ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ๋Œ€ํ•œ ์ „์ฒด์ ์ธ ๋ฆฌํŒฉํ† ๋ง์„ ์ง„ํ–‰ํ•œ ํ›„ ๋‘ ํ…Œ์ด๋ธ” portfolio์™€ portfolioSubject๋กœ ๋ถ„๋ฆฌํ–ˆ๋‹ค.

ํฌํŠธํด๋ฆฌ์˜ค์˜ ์ •๋ณด๋ฅผ ์‚ฌ์šฉ์ž์—๊ฒŒ ๋ฟŒ๋ ค์ค„ ๋•Œ ์šฐ๋ฆฌ๋Š” portfolio ํ…Œ์ด๋ธ” ๋‚ด์˜ ์ •๋ณด ๋ฟ ์•„๋‹ˆ๋ผ portfolioSubject ํ…Œ์ด๋ธ” ๋‚ด์˜ ์ •๋ณด๋„ ํ•„์š”ํ–ˆ๋‹ค. JOIN์„ ์ด์šฉํ•ด์•ผ ํ–ˆ๊ณ , subject ์ปฌ๋Ÿผ์˜ ์ •๋ณด๋“ค์€ ๋ฐฐ์—ด์˜ ํ˜•ํƒœ๋กœ ์–ป๊ณ  ์‹ถ์—ˆ๋‹ค. ๊ทธ๋ ‡๊ฒŒ ๊ฒ€์ƒ‰์„ ์ง„ํ–‰ํ•˜๋˜ ์ค‘ group_concat()๋ฅผ ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค.

๐ŸŽ ๊ทธ๋ž˜์„œ ์–ด๋–ป๊ฒŒ ์‚ฌ์šฉํ•ด?

์„œ๋ก ์ด ๊ธธ์—ˆ๋‹ค.

์‚ฌ์šฉ ์˜ˆ์‹œ๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

SELECT p.mento, p.brief, p.mentoPic, p.content, p.curDate, p.score, group_concat(ps.subject)
FROM portfolio p JOIN portfolioSubject ps ON p.id=ps.portfolio
GROUP BY p.mento

์ฟผ๋ฆฌ ์‹คํ–‰ ์‹œ ๊ฒฐ๊ณผ๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

๊ทธ๋Ÿฌ๋‚˜, ์—ฌ๊ธฐ์„œ ์ฃผ์˜ํ•ด์•ผ ํ•  ์ ์€ GROUP BY๋กœ ๋‚˜๋ˆ„์–ด์ง„ row๋กœ ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•œ๋‹ค๋Š” ์ .

์œ„ ์ฟผ๋ฆฌ๋ฌธ์—์„œ GROUP BY๋ฅผ ์ ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด
GROUP_CONCAT(subject)์˜ ๊ฒฐ๊ณผ๋Š” 1, 2, 3, 6, 8 ์ด ๋  ๊ฒƒ์ด๋‹ค.

์„ธ์ƒ์—๋Š” ์ •๋ง ๋‹ค์–‘ํ•œ ์ฟผ๋ฆฌ๋ฌธ์ด ์žˆ๋‹ค. ํŒŒ๋„ ํŒŒ๋„ ๋์ด ์—†๋‹ค.
ํ‰์ƒ์„ ์‚ด์•„๋„ ๊ณต๋ถ€ํ•  ๊ฒŒ ๋งŽ๋‹ค๋Š” ์‚ฌ์‹ค์€ ์ฐธ ์„ ๋ฌผ ๊ฐ™๋‹ค. ๐ŸŽ

profile
์„ฑ์žฅ ์ค‘๋… | ์„œ๋ฒ„, ๋ฐ์ดํ„ฐ, ์ •๋ณด ๋ณด์•ˆ์„ ๊ณต๋ถ€ํ•ฉ๋‹ˆ๋‹ค.

1๊ฐœ์˜ ๋Œ“๊ธ€

comment-user-thumbnail
2023๋…„ 7์›” 26์ผ

์ž˜ ์ฝ์—ˆ์Šต๋‹ˆ๋‹ค. ์ข‹์€ ์ •๋ณด ๊ฐ์‚ฌ๋“œ๋ฆฝ๋‹ˆ๋‹ค.

๋‹ต๊ธ€ ๋‹ฌ๊ธฐ