๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
[๊ฐœ๋ฐœ] Practice/SQL Database

[SQL / Database] UNION ์‚ฌ์šฉํ•˜์—ฌ ํ…Œ์ด๋ธ” ํ•ฉ์น˜๊ธฐ

by Connecting-the-dots 2023. 6. 3.
728x90
๋ฐ˜์‘ํ˜•

๐Ÿ’กUNION ์‚ฌ์šฉํ•˜์—ฌ ํ…Œ์ด๋ธ” ํ•ฉ์น˜๊ธฐ

  • ํ…Œ์ด๋ธ”์„ ํ•ฉ์น˜๋Š” ๋ฐฉ๋ฒ•์—๋Š” ๋Œ€ํ‘œ์ ์œผ๋กœ JOIN ๊ณผ UNION ์ด ์žˆ๋‹ค.
    • JOIN ์˜ ๊ฒฝ์šฐ ํ…Œ์ด๋ธ”์„ ์–‘์˜†์œผ๋กœ ๋ถ™์ผ ๋•Œ ์‚ฌ์šฉํ•˜๋ฉฐ, UNION ์€ ์œ„์•„๋ž˜๋กœ ๋ถ™์ผ ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

๐Ÿ’œ UNION ์œผ๋กœ ํ…Œ์ด๋ธ” ํ•ฉ์น˜๊ธฐ

SELECT * FROM ํ…Œ์ด๋ธ”๋ช…1 UNION SELECT * FROM ํ…Œ์ด๋ธ”๋ช…2;
  • ๋น„์Šทํ•œ ์–‘์‹์˜ ํ…Œ์ด๋ธ”๋“ค์„ ํ•œ๋ฒˆ์— ์ถœ๋ ฅํ•˜๊ณ  ์‹ถ์„ ๋•Œ UNION ์„ ์‚ฌ์šฉํ•˜๋ฉฐ, ๊ฐ SELECT ๋ฌธ ์‚ฌ์ด์— UNION ์„ ๋ถ™์—ฌ์ค€๋‹ค.
    • UNION ์€ ํ…Œ์ด๋ธ”์„ ์œ„์•„๋ž˜๋กœ ํ•ฉ์น˜๋Š” ๊ฒƒ์ด๋ฏ€๋กœ, ๋‹น์—ฐํžˆ ๊ฐ ํ…Œ์ด๋ธ”์—์„œ ์ถœ๋ ฅํ•  ์ปฌ๋Ÿผ ๊ฐœ์ˆ˜๋Š” ๋™์ผํ•ด์•ผ ํ•œ๋‹ค.
    • ์ปฌ๋Ÿผ๋ช…์€ ๋‹ฌ๋ผ๋„ ์ถœ๋ ฅ์€ ๊ฐ€๋Šฅํ•˜์ง€๋งŒ ์‚ฌ์šฉํ•  ํ•„์š”์„ฑ์ด ์—†์œผ๋ฏ€๋กœ ๊ฐ€๋Šฅํ•˜๋‹ค๋Š” ์ ๋งŒ ์•Œ์•„๋‘์ž!
  • ๊ฐ™์€ ํ…Œ์ด๋ธ”์˜ ์ถœ๋ ฅ๊ฒฐ๊ณผ๋„ UNION ์„ ์‚ฌ์šฉํ•˜๋ฉด ํ•˜๋‚˜๋กœ ํ•ฉ์น  ์ˆ˜ ์žˆ์ง€๋งŒ, WHERE ๋ฌธ๋ฒ•์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒŒ ๋” ํšจ์œจ์ ์ด๋ฏ€๋กœ ๊ตณ์ด ์‚ฌ์šฉํ•˜์ง€๋Š” ์•Š๋Š”๋‹ค.
  • UNION ์€ ํ•ฉ์นœ ๊ฒฐ๊ณผ๋ฌผ์—์„œ ์ž๋™์œผ๋กœ ์ค‘๋ณต์„ ์ œ๊ฑฐํ•˜๋ฏ€๋กœ, ์ค‘๋ณต์ œ๊ฑฐ๋ฅผ ์›์น˜ ์•Š๋Š”๋‹ค๋ฉด UNION ALL ์„ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

๐Ÿ’œ UNION ALL ๋กœ ํ…Œ์ด๋ธ” ํ•ฉ์น˜๊ธฐ

SELECT * FROM ํ…Œ์ด๋ธ”๋ช…1 UNION ALL SELECT * FROM ํ…Œ์ด๋ธ”๋ช…2;
  • UNION ALL ์€ ํ•ฉ์นœ ๊ฒฐ๊ณผ๋ฌผ์—์„œ ์ค‘๋ณต์ œ๊ฑฐ๋ฅผ ์›์น˜ ์•Š์„ ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.
728x90
๋ฐ˜์‘ํ˜•