본문 바로가기
학교 강의/데이터베이스

9주차 조인, 서브쿼리

by hoshi03 2023. 10. 27.

시험에 나오는 유형, 책 103p, 교집합 차집합 내용 다시 보자

-- 책을 한번도 안산 고객을 가져오기
select name from customer c 
where custid not in (select custid from orders)

 

 

left outer join으로 customer의 데이터 전체와 orders에서 customer와 연관있는 데이터를 가져왔다

join은 on으로 조건을 표현한다

-- 책을 주문한 고객의 이름과 주문, 책을 출력
select c.name, o.saleprice
from customer c left outer join orders o
on c.custid = o.custid;

 

서브쿼리 - where절에 select문을 넣어서 조건을 만드는 것

-- 가격이 가장 비싼 책의 이름, 가격
select bookname, price from book
where book.price = (select max(price) from book);
-- 도서테이블의 책가격의 전체평균보다 책 가격이 비싼 책의 이름, 출판사, 가격을 검색
select bookname, price, publisher from book
where book.price >= (select avg(price) from book);

 

부질의로 여러개의 값을 가져오는 것도 가능하다, 여러개의 값을 가져올때는 in을 사용

-- 책제목에 축구가 있는 출판사와 같은 출판사 책의 이름과 출판사 출력
select bookname, publisher from book
where publisher in (select publisher from book where bookname like '%축구%');

 

-- 김연아가 주문한 책의 총합계를 부질의를 이용해서 검색
select sum(saleprice) from orders o
where custid = (select custid from customer where name = '김연아');

select sum(saleprice) from orders o, customer c
where c.custid = o.custid and c.name = '김연아';

조인, 서브쿼리 종합, b.bookid로 어느 테이블의 bookid인지 구별해줘야한다

-- 고객번호가 3번인 고객과 같은 책을 주문한 고객의 이름, 책 제목
select c.name, b.bookname from customer c, book b, orders o
where o.custid = c.custid and o.bookid = b.bookid 
and b.bookid in (select bookid from orders o where custid = 3);

집합 연산자 union - 합집합 , in - 교집합, not in - 차집합

 

select name from customer where address like '%영국%'
union
select name from customer
where custid not in(select custid from orders);

Exsist 연산자 : 조건절을 만족하는 모든 일치하는 값을 검색


-- 책을 주문한 고객의 이름과 주소를ㄹ 검색
select name, address from customer c 
where exists (select * from orders o where c.custid = o.custid);

 

-- 트랜잭션 : 백업, 모든 작업들을 복구 : rollback, 수락 : commit
start transaction;

rollback;

 

-- 삽입 insert into 테이블 (속성명) values ()
insert into book  values(111,'데이터베이스','한양출판사',25000);
insert into book (bookid,price,bookname) values (12,30000,'프로그래밍');

-- 변경 update 테이블명 set 바꿀값, 바꿀값 where 기본키 값  alter
-- 책번호 12번인 책의 출판사를 한양출판사, 가격을 28000
update book 
set publisher = '한양출판사', price = 28000 
where bookid = 12; 

delete from book where bookid = 111;

'학교 강의 > 데이터베이스' 카테고리의 다른 글

페이징  (0) 2023.10.29
조인, 서브쿼리 조금 더 알아본 내용  (0) 2023.10.29
데베시험대비  (0) 2023.10.18
6주차 - 조인 시험에 많이 나옴  (0) 2023.10.13
5주차  (1) 2023.10.06