다수의 SQL문을 합쳐서 하나의 SQL문으로 만들어주는 것 (컬럼 개수가 같아야 함)
select * from test1
union all | union
select * from test2;
select * from celeb where sex='F'
union all | union
select * from celeb where agency='YG';
# 컬럼 개수만 맞으면 오류 없이 결과가 나오지만 원하는 형태는 아니다.
select name, job_title from celeb where job_title = 'singer'
union
select name, birthday from celeb where birthday between 19800101 and 19891231;
두 개 이상의 테이블을 결합하는 것
select celeb.id, celeb.name, snl_show.id, snl_show.host
from celeb
inner join snl_show
on celeb.name = snl_show.host;
select celeb.id, celeb.name, snl_show.id, snl_show.host
from celeb
left join snl_show
on celeb.name = snl_show.host;
select celeb.id, celeb.name, snl_show.id, snl_show.host
from celeb
right join snl_show
on celeb.name = snl_show.host;
➡ MySQL에서 지원하지 않음
select celeb.id, celeb.name, snl_show.id, snl_show.host
from celeb
full outer join snl_show
on celeb.name = snl_show.host;
>>>
ERROR 1064 (42000): You have an error in your SQL syntax;
FULL OUTER JOIN 과 같은 결과를 만들고 싶다면?
select celeb.id, celeb.name, snl_show.id, snl_show.host
from celeb left join snl_show on celeb.name = snl_show.host
union
select celeb.id, celeb.name, snl_show.id, snl_show.host
from celeb right join snl_show on celeb.name = snl_show.host;
INNER JOIN과 같은 결과를 가져옴
select celeb.id, celeb.name, snl_show.id, snl_show.host
from celeb, snl_show
where celeb.name = snl_show.host;
select celeb.name, celeb.job_title
from celeb, snl_show
where celeb.name = snl_show.host and celeb.agency='antenna';
select celeb.name, celeb.age, celeb.job_title, celeb.agency,
snl_show.season, snl_show.episode
from celeb, snl_show
where celeb.name = snl_show.host
and ((not job_title like '%actor%' and agency='YG')
or (age >= 40 and not agency='YG'));
동일한 컬럼명이 존재하는 경우에는 반드시 테이블명을 써줘야 한다.
select snl_show.id, season, episode, name, job_title
from celeb, snl_show
where celeb.name = snl_show.host;
# 가독성을 위해 모든 컬럼에 테이블명을 써주자!
select snl_show.id, snl_show.season, snl_show.episode,
celeb.name, celeb.job_title
from celeb, snl_show
where celeb.name = snl_show.host;
select name, season, episode, broadcast_date, agency
from celeb, snl_show
where celeb.name = snl_show.host
and (episode in (7, 9, 10) or agency like 'Y%')
and broadcast_date >= 20200915;
select celeb.id, celeb.name, snl_show.season, snl_show.episode
from celeb, snl_show
where celeb.name = snl_show.host
and not (job_title like '%actor%' or job_title like '%talent%');
# snl_show에 출현한 celeb 중에서
# 작년 9월 15일 이후에 출연했거나 소속사 이름이 G로 끝나지 않으면서
# actor나 comedian이 아닌 연예인의
# celeb 아이디, 이름, 직업, 소속사 검색
select celeb.id, celeb.name, celeb.job_title, celeb.agency
from celeb, snl_show
where celeb.name = snl_show.host
and (broadcast_date > 20200915 or not agency like '%G')
and not (job_title like '%actor%' or job_title like '%comedian%');