DB/명령프롬프트 - mysql 예시

[MySQL] 뷰 view 생성 예제

congs 2023. 3. 30. 12:45

1학기 수업을 듣는 학생들을 검색

  • 출력: 학번, 이름
  • 조건: 1학기 / 중복제거 
  • 추가 출력: 과목이름
  • 중복제거를 하지 않는 경우 !
    • 조건에 맞는 학생이름 전체 출력, 조건에 맞는 번호 전체 출력 = 2번출력
-- 학번, 이름, 중복제거
mysql> create or replace view 1term_view as
    -> select distinct s.st_name, s.st_num
    -> from student as s, course as c
    -> where c.co_term = 1;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from 1term_view;
+---------+------------+
| st_name | st_num     |
+---------+------------+
| 김영철  | 2020123001 |
| 나영희  | 2020123002 |
| 강철수  | 2020160001 |
| 박철수  | 2020160002 |
| 강군    | 2020456001 |
+---------+------------+
5 rows in set (0.00 sec)

-- 추가 출력 : 과목명 추가
mysql> create or replace view 1term_view as
    -> select distinct s.st_name, s.st_num, su.su_title
    -> from student as s, course as c, subject as su
    -> where c.co_term = 1;
Query OK, 0 rows affected (0.01 sec)

mysql> select * from 1term_view;
+---------+------------+------------+
| st_name | st_num     | su_title   |
+---------+------------+------------+
| 강군    | 2020456001 | 대학수학   |
| 박철수  | 2020160002 | 대학수학   |
| 강철수  | 2020160001 | 대학수학   |
| 나영희  | 2020123002 | 대학수학   |
| 김영철  | 2020123001 | 대학수학   |
| 강군    | 2020456001 | 컴퓨터개론 |
| 박철수  | 2020160002 | 컴퓨터개론 |
| 강철수  | 2020160001 | 컴퓨터개론 |
| 나영희  | 2020123002 | 컴퓨터개론 |
| 김영철  | 2020123001 | 컴퓨터개론 |
| 강군    | 2020456001 | 운영체제   |
| 박철수  | 2020160002 | 운영체제   |
| 강철수  | 2020160001 | 운영체제   |
| 나영희  | 2020123002 | 운영체제   |
| 김영철  | 2020123001 | 운영체제   |
| 강군    | 2020456001 | 글쓰기     |
| 박철수  | 2020160002 | 글쓰기     |
| 강철수  | 2020160001 | 글쓰기     |
| 나영희  | 2020123002 | 글쓰기     |
| 김영철  | 2020123001 | 글쓰기     |
| 강군    | 2020456001 | 영어       |
| 박철수  | 2020160002 | 영어       |
| 강철수  | 2020160001 | 영어       |
| 나영희  | 2020123002 | 영어       |
| 김영철  | 2020123001 | 영어       |
+---------+------------+------------+
25 rows in set (0.00 sec)

 

  • 과목명을 사람당 한줄로 출력하는 방법
    • group_concat(distinct b.su_title)을 이용하여 과목명을 그룹으로 묶고 연결해 출력
mysql> create or replace view 1term_view as
    -> select s.st_num, s.st_name, group_concat(distinct b.su_title) from
    -> student as s, course as c, subject as b
    -> where c.co_term = 1
    -> group by s.st_num, s.st_name;
Query OK, 0 rows affected (0.01 sec)

mysql> select * from 1term_view;
+------------+---------+------------------------------------------+
| st_num     | st_name | group_concat(distinct b.su_title)        |
+------------+---------+------------------------------------------+
| 2020123001 | 김영철  | 글쓰기,대학수학,영어,운영체제,컴퓨터개론 |
| 2020123002 | 나영희  | 글쓰기,대학수학,영어,운영체제,컴퓨터개론 |
| 2020160001 | 강철수  | 글쓰기,대학수학,영어,운영체제,컴퓨터개론 |
| 2020160002 | 박철수  | 글쓰기,대학수학,영어,운영체제,컴퓨터개론 |
| 2020456001 | 강군    | 글쓰기,대학수학,영어,운영체제,컴퓨터개론 |
+------------+---------+------------------------------------------+
5 rows in set (0.00 sec)