Post

๐Ÿฃ 7. Database

SQL ๋ฌธ๋ฒ•๊ณผ ๊ทธ ๋ณ€์ข…๋“ค

  • ๋ฌต์‹œ์  JOIN
    1
    2
    3
    
    SELECT CourseName, TeacherName
    FROM Courses INNER JOIN Teachers
    ON Courses.TeacherID = Teachers.TeacherID
    
  • ๋ช…์‹œ์  JOIN
    1
    2
    3
    
    SELECT CourseName, TeacherName
    FROM Courses
    WHERE Courses.TeacherID = Teachers.TeacherID
    

๋น„์ •๊ทœํ™” ๐Ÿ†šย ์ •๊ทœํ™” ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค

  • ์ •๊ทœํ™” ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค : ์ค‘๋ณต์„ ์ตœ์†Œํ™”ํ•˜๋„๋ก ์„ค๊ณ„๋œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค
  • ๋น„์ •๊ทœํ™” ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค : ์ฝ๋Š” ์‹œ๊ฐ„์„ ์ตœ์ ํ™”ํ•˜๋„๋ก ์„ค๊ณ„๋œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค

  • ์ „ํ˜•์ ์ธ ์ •๊ทœํ™” ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค : ์™ธ๋ž˜ํ‚ค๋ฅผ ๊ฐ–๋Š” ์—ด ์กด์žฌ
    • ์žฅ์ 
      • ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ํ•œ ๋ฒˆ๋งŒ ์ €์žฅํ•ด๋„ ๋œ๋‹ค.
      • ์ƒ๋‹น์ˆ˜์˜ ์ผ์ƒ์  ์งˆ์˜ โ†’ JOIN์„ ๋งŽ์ด ํ•˜๊ฒŒ ๋˜๋Š” ๋‹จ์ 
    • ๋น„์ •๊ทœํ™” ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค
      • ๋ฐ์ดํ„ฐ๋ฅผ ์ค‘๋ณตํ•ด์„œ ์ €์žฅ ๊ฐ€๋Šฅ
      • ๋†’์€ ๊ทœ๋ชจ ํ™•์žฅ์„ฑ ์‹คํ˜„ ๊ฐ€๋Šฅ

SQL ๋ฌธ

  • ํ•™์ƒ ๋“ฑ๋ก ์งˆ์˜๋ฌธ
1
2
3
4
5
6
7
8
/* ๋‹ค๋ฅธ ์งˆ์˜๋ฌธ์œผ๋กœ ๊ฐ์‹ธ๊ธฐ */
SELECT StudentName, Students.StudentID, Cnt
FROM (
		SELECT Students.StudentID, count(StudentCourses.CourseID) as [Cnt]
		FROM Students LEFT JOIN StudentCourses
		ON Students.StudentID = StudentCourses.StudentID
		GROUP BY Students.StudentID
) T INNER JOIN Students on T.studentID = StudentID;
1
2
3
4
5
/* StudentName์„ GROUP BY ์ ˆ์— ์ถ”๊ฐ€ํ•˜๊ธฐ */
SELECT StudentName, Students.StudentID, count(StudentCourses.CourseID) as [Cnt]
FROM Students LEFT JOIN StudentCourses
ON Students.StudentID = StudentCourses.StudentID
GROUP BY Students.StudentID, Students.StudentName;
1
2
3
4
5
6
/* ์ง‘ํ•ฉ ํ•จ์ˆ˜๋กœ ๊ฐ์‹ธ๊ธฐ */
SELECT max(StudentName) as [StudentName], Students.StudentID,
		count(StudentCourses.CourseID) as [Count]
FROM Students LEFT JOIN StudentCourses
ON Students.StudentID = StudentCourses.StudentID
GROUP BY Students.StudentID;

์†Œ๊ทœ๋ชจ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์„ค๊ณ„

  • 1๋‹จ๊ณ„: ๋ชจํ˜ธ์„ฑ ์ฒ˜๋ฆฌ
    • ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๊ด€๋ จ ๋ฌธ์ œ : ๋ชจํ˜ธํ•œ ๋ถ€๋ถ„์ด ๋‚ดํฌ
    • ์„ค๊ณ„ ์ „ ์ •ํ™•ํžˆ ๋ฌด์—‡์„ ์„ค๊ณ„ํ•ด์•ผํ•˜๋Š” ์ง€ ์ดํ•ด
  • 2๋‹จ๊ณ„ : ํ•ต์‹ฌ ๊ฐ์ฒด ์ •์˜
    • ํ•ต์‹ฌ ๊ฐ์ฒด(core object)๊ฐ€ ๋ฌด์—‡์ธ์ง€ ์ •์˜
  • 3๋‹จ๊ณ„ : ๊ด€๊ณ„ ๋ถ„์„
    • ํ…Œ์ด๋ธ”๋ผ๋ฆฌ์˜ ๊ด€๊ณ„ ํŒŒ์•…
    • ์ผ๋Œ€๋‹ค
    • ๋‹ค๋Œ€๋‹ค
  • 4๋‹จ๊ณ„ : ํ–‰์œ„ ์กฐ์‚ฌ
    • ์„ธ๋ถ€์ ์ธ ๋ถ€๋ถ„ ์ฑ„์›Œ๋„ฃ๊ธฐ

๋Œ€๊ทœ๋ชจ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์„ค๊ณ„

  • JOIN ์—ฐ์‚ฐ์€ ์•„์ฃผ ๋Š๋ฆฌ๋‹ค๊ณ  ๊ฐ„์ฃผ
  • ๋ฐ์ดํ„ฐ ๋น„์ •๊ทœํ™”๊ฐ€ ์ค‘์š”
This post is licensed under CC BY 4.0 by the author.