DBMS Day11 UNION, SELECT 예제

김지원·2022년 6월 23일
0

DBMS

목록 보기
11/17

-> scores 테이블 열 추가

사진과 같이 SELECT 하시오

SELECT `test`.`name`                         AS `시험`,
       `score`.`execution_from`              AS `시작일`,
       `score`.`execution_to`                AS `종료일`,
       CONCAT(`score`.`student_grade`, '학년 ',
              `score`.`student_class`, '반 ',
              `score`.`student_number`, '번') AS `식별자`,
       `student`.`name`                      AS `학생명`,
       `subject`.`name`                      AS `과목명`,
       `score`.`score`                       AS `점수`
FROM `school`.`scores` AS `score`
         LEFT JOIN `school`.`tests` AS `test` ON `score`.`execution_test_code` = `test`.`code`
         LEFT JOIN `school`.`students` AS `student` ON `score`.`student_grade` = `student`.`grade` AND 
                                                       `score`.`student_class` = `student`.`class` AND 
                                                       `score`.`student_number` = `student`.`number`
         LEFT JOIN `school`.`subjects` AS `subject` ON `score`.`subject_code` = `subject`.`code`;

 LEFT JOIN `school`.`tests` AS `test` ON `score`.`execution_test_code` = `test`.`code`
  • scores테이블과 tests 테이블의 직접적인 연관은 없지만 executions테이블이 scores테이블에 대한 무결성을 보증하기 때문에 tests와 JOIN을 걸어서 사용해도 무결성을 해치지 않는다.

UNION

: 전/후로 오는 SELECT 결과를 하나의결과로 결합한다. 단, 전/후로 오는 SELECT 결과의 열의 개수가 같아야한다.

  • 2개이상의 SELECT를 합치고 싶을 떄 사용한다.
  • ; (세미콜론)은 항상 마지막에만 사용한다.
SELECT 1,2,3
UNION
SELECT 4,5,6
UNION
SELECT 7,8,9;

SELECT 1,2,3
UNION
SELECT 4,5,6
UNION
SELECT 7,8,9,10;

  • SELECT 결과의 열의 개수가 같지않으면 오류가 뜬다.

AVG(x) AVERAGE

: x열 값의 평균

SELECT AVG(`score`)
FROM `school`.`scores` AS `score`;

사진과 같이 UMION을 사용하여 SELECT 하시오

SELECT `test`.`name`                         AS `시험`,
       `score`.`execution_from`              AS `시작일`,
       `score`.`execution_to`                AS `종료일`,
       CONCAT(`score`.`student_grade`, '학년 ',
              `score`.`student_class`, '반 ',
              `score`.`student_number`, '번') AS `식별자`,
       `student`.`name`                      AS `학생 이름`,
       `subject`.`name`                      AS `과목명`,
       `score`.`score`                       AS `점수`
FROM `school`.`scores` AS `score`
         LEFT JOIN `school`.`tests` AS `test` ON `score`.`execution_test_code` = `test`.`code`
         LEFT JOIN `school`.`students` AS `student` ON `score`.`student_grade` = `student`.`grade` AND
                                                       `score`.`student_class` = `student`.`class` AND
                                                       `score`.`student_number` = `student`.`number`
         LEFT JOIN `school`.`subjects` AS `subject` ON `score`.`subject_code` = `subject`.`code`
UNION
SELECT '평균', NULL, NULL, NULL, NULL, NULL,
       AVG(`score`)
FROM `school`.`scores` AS `score`;
profile
Software Developer : -)

0개의 댓글