본문 바로가기
공부/데이터베이스

데이터베이스 - SQL, join table

by 라이티아 2025. 11. 3.

조인 = join은 두 개 이상의 테이블을 묶어 하나의 결과 테이블을 생성함

 

예제)

cookDB

userTBL = 회원정보

buyTBL = 구매 정보

 

한 회원이 여러 개의 구매 기록을 가짐

userTBL - buyTBL을 join으로 엮어서 구매내역 조회

 

 

내부 조인 inner join

일반적인 조인을 지칭함, 가장 많이 사용되는 조인 방식

두 테이블의 내부 조인

select 열 from 첫테이블 join 두번째테이블 on 조인될조건 where 검색조건

 

KYM이라는 아이디를 가진 회원이 구매한 물건을 발송하려면?

use cookdb;

select * from buytbl as b join usertbl as u on b.userID = u.userID where b.userID = 'KYM';

 

내부 조인의 작동 과정

b.userID에서 회원 아이디 추출

u.userID에서 동인한 값 추출

아이디 기준으로 두 테이블을 결합 = 조인

 

조인으로 속성을 찾을시 '테이블이름.테이블속성이름'을 맞춰 주어야 한다

 

use cookdb;

select userID, userName, prodName, addr, concat(mobile1, mobile2) as '연락처' from buytbl as b join usertbl as u on b.userID = u.userID;

만약 없이 조회를 하면

오류로 처리가 된다

 

use cookdb;

select b.userID, u.userName, b.prodName, u.addr, concat(u.mobile1, u.mobile2) as '연락처' from buytbl as b join usertbl as u on b.userID = u.userID;

잘 나오는 것을 확인할 수 있다

 

 

Q. 이때 join을 A, B로 거는것과 B, A로 거는 것은 결과가 같은가?

 A. 결과는 같다

 

오른쪽 왼쪽 규칙 같은것은 없다

 

inner의 경우는 차이가 없지만

outer의 경우는 차이가 난다

 

use cookdb;

select distinct u.userID, u.userName, u.addr from usertbl as u join buytbl as b
on u.userID = b.userID order by u.userID;

select u.userID, u.userName, u.addr
from usertbl as u
where exists (
  select * from buytbl as b
  where b.userID = u.userID
);

같은 결과를 내지만 다르게 표현이 가능하다

 

예제 문제)

강의와 교수 테이블이 있을시 이를 연결하시오

use schooldb;

select c.course_id, c.title, p.name from course as c join professor as p on c.prof_id = p.prof_id;

 

시험에 나온다면?

prof_id = 1인 사람만 조회

혹은 이름으로 조회

 

use schooldb;

select e.enroll_id, s.name, c.title
from enroll e
join course c
on e.course_id = c.course_id
join student s
on e.student_id = s.student_id;

3중 조인도 같은 형식으로 사용할 수 있다

 

 

외부 조인 outer join

조인 조건을 만족하지 않는 행까지 포함하여 출력하는 조인

use cookdb;

select u.userID, u.userName, b.prodName, u.addr, concat(u.mobile1, u.mobile2) as '연락처'
	from usertbl u
		left outer join buytbl b
			on u.userID = b.userID
		order by u.userID;

 

구매가 없는 사람도 조회가 된다

 

use cookdb;

select u.userID, u.userName, b.prodName, u.addr, concat(u.mobile1, u.mobile2) as '연락처'
	from buytbl b
		right outer join usertbl u
			on u.userID = b.userID
		order by u.userID;

left right를 변경시 테이블도 바꾸면 그대로 유지 된다

 

where로 엮어서 반대 성향 찾기를 할 수 있다

 

use schooldb;

select *
	from student s
		left join enroll e
			on e.student_id = s.student_id
		where e.enroll_id is null;

outer 조인의 경우 찾는 중요 내용 테이블을 앞으로 돌려야 원하는 데이터를 찾을 수 있다