EEALL@ONCE

๐Ÿ“Š์„œ๋ธŒ ์ฟผ๋ฆฌ : ์ง‘๊ณ„ vs inner join : ๊ฒฐํ•ฉ ๋ณธ๋ฌธ

Data๐Ÿ“Š/SQL ์ฟผ๋ฆฌ ์Šคํ„ฐ๋””

๐Ÿ“Š์„œ๋ธŒ ์ฟผ๋ฆฌ : ์ง‘๊ณ„ vs inner join : ๊ฒฐํ•ฉ

์˜ฌ์—ฃ์›์Šค 2023. 8. 16. 18:55
728x90

`bill_acc_id`๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๊ทธ๋ฃนํ™”ํ•˜์—ฌ `aply_amt` ๊ฐ’์„ ๋ชจ๋‘ ๋”ํ•˜๊ณ , ๊ทธ ๊ฒฐ๊ณผ๋ฅผ `total_deposit` ์ปฌ๋Ÿผ์— ์—…๋ฐ์ดํŠธํ•˜๋ ค๋Š” ๊ฒƒ์œผ๋กœ ์ดํ•ดํ•˜์˜€์Šต๋‹ˆ๋‹ค.

์•„๋ž˜์˜ SQL ์ฟผ๋ฆฌ๋Š” ๊ทธ ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•˜๋Š” ์˜ˆ์‹œ์ž…๋‹ˆ๋‹ค.

1. ๋จผ์ €, `bill_acc_id`๋ฅผ ๊ธฐ์ค€์œผ๋กœ `aply_amt` ๊ฐ’์„ ๋”ํ•˜๋Š” ์ฟผ๋ฆฌ๋ฅผ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค.
2. ๊ทธ ๋‹ค์Œ, ๊ทธ ๊ฒฐ๊ณผ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ `tb_rmny` ํ…Œ์ด๋ธ”์˜ `total_deposit` ์ปฌ๋Ÿผ์„ ์—…๋ฐ์ดํŠธํ•ฉ๋‹ˆ๋‹ค.

UPDATE tb_rmny
SET total_deposit = (
  SELECT SUM(aply_amt)
  FROM tb_rmny AS subquery
  WHERE subquery.bill_acc_id = tb_rmny.bill_acc_id
)




์ด ์ฟผ๋ฆฌ๋Š” `tb_rmny` ํ…Œ์ด๋ธ” ๋‚ด์— ๊ฐ™์€ `bill_acc_id`๋ฅผ ๊ฐ€์ง„ ํ–‰๋“ค์˜ `aply_amt` ๊ฐ’์„ ๋ชจ๋‘ ๋”ํ•˜๊ณ , ๊ทธ ๊ฒฐ๊ณผ๋ฅผ ํ•ด๋‹น ๊ทธ๋ฃน์˜ `total_deposit` ์ปฌ๋Ÿผ์— ํ• ๋‹นํ•ฉ๋‹ˆ๋‹ค.

 




์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ด์œ ๋Š” ๋™์ผํ•œ ํ…Œ์ด๋ธ” ๋‚ด์—์„œ `bill_acc_id` ๋ณ„๋กœ ๊ทธ๋ฃนํ™”๋ฅผ ํ•˜๊ธฐ ์œ„ํ•ด์„œ์ž…๋‹ˆ๋‹ค.

INNER JOIN์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ์™€์˜ ์ฐจ์ด๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค:

1. **์ฟผ๋ฆฌ ๊ตฌ์กฐ**: ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ์‹์€ ํ•ด๋‹น ์ปฌ๋Ÿผ์„ ์ง์ ‘ ์—…๋ฐ์ดํŠธํ•˜๋Š” ๋ฐ ์ดˆ์ ์„ ๋งž์ถ”๊ณ  ์žˆ์œผ๋ฉฐ, INNER JOIN์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ๋Š” ์ผ๋ฐ˜์ ์œผ๋กœ ๋‘ ๊ฐœ ์ด์ƒ์˜ ํ…Œ์ด๋ธ” ๊ฐ„ ๊ด€๊ณ„๋ฅผ ์ด์šฉํ•˜์—ฌ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฒฐํ•ฉํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.

2. **์šฉ๋„**: ์„œ๋ธŒ์ฟผ๋ฆฌ ๋ฐฉ์‹์€ ๋™์ผํ•œ ํ…Œ์ด๋ธ”์—์„œ ํŠน์ • ์กฐ๊ฑด์— ๋”ฐ๋ฅธ ์ง‘๊ณ„๋ฅผ ์ˆ˜ํ–‰ํ•˜์—ฌ ๊ฒฐ๊ณผ๋ฅผ ์—…๋ฐ์ดํŠธํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค. INNER JOIN์€ ์„œ๋กœ ๋‹ค๋ฅธ ํ…Œ์ด๋ธ” ๊ฐ„์— ๊ณตํ†ต ์ปฌ๋Ÿผ์„ ๊ธฐ์ค€์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฒฐํ•ฉํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.


INNER JOIN์„ ์‚ฌ์šฉํ•˜์—ฌ ๋™์ผํ•œ ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•˜๋ ค๋ฉด, ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ฟผ๋ฆฌ๊ฐ€ ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

UPDATE tb_rmny
INNER JOIN (
  SELECT bill_acc_id, SUM(aply_amt) AS sum_amt
  FROM tb_rmny
  GROUP BY bill_acc_id
) AS subquery ON tb_rmny.bill_acc_id = subquery.bill_acc_id
SET tb_rmny.total_deposit = subquery.sum_amt;



728x90