[제로베이스 데이터 분석 스쿨 2기] SQL (feat. Union, Join, Concat, Alias, Distinct, Limit)

박세우·2024년 1월 23일

Union

여러 개의 SQL문을 합쳐서 하나의 SQL 문으로 만들어주는 방법 (주의, 칼럼의 개수가 같아야함)

Union: 중복된 값을 제거하여 알려준다.
Union ALL: 중복된 값도 모두 보여준다.

select col1, col2 from table A
Union | Union ALL
select col1, col2 from table B;

Join

두 개 이상의 테이블을 결합하는 것

출처 - 제로베이스

Inner join

두 개의 테이블에서 공통된 요소들을 통해 결합하는 조인방식

select col1, col2, ...
from tableA
inner join tableB
on tableA.column = tableB.column
where condition;

select celeb.id, celeb.name, snlshow.id, snlshow.host
from celeb
inner join snlshow
on celeb.name = snlshow.host;

Left join

두 개의 테이블에서 공통영역을 포함해 왼쪽 테이블의 다른 대이터를 포함하는 조인방식

select col1, col2, ...
from tableA
left join tableB
on tableA.column = tableB.column
where condition;

select celeb.id, celeb.name, snlshow.id, snlshow.host
from celeb
left join snlshow
on celeb.name = snlshow.host;

Right join

두 개의 테이블에서 공통영역을 포함해 오른쪽 테이블의 다른 데이터를 포함하는 조인방식

select col1, col2, ...
from tableA
right join tableB
on tableA.column = tableB.column
where condition;

select celeb.id, celeb.name, snlshow.id, snlshow.host
from celeb
right join snlshow
on celeb.name = snlshow.host;

Full outer join

두 개의 테이블에서 공통영역을 포함하여 양쪽 테이블의 다른 영역을 모두 포함하는 조인방식 (MySQL에서 지원 안함)

select col1, col2, ...
from tableA
full outer join tableB
on tableA.column = tableB.column
where condition;

MySQL에서는 FULL JOIN을 지원하지 않으므로 다음의 쿼리로 같은 결과를 만들 수 있다.

select col1, col2, ...
from tableA
left join tableB
on tableA.column = tableB.column

UNION

select col1, col2, ...
from tableA
right join tableB
on tableA.column = tableB.column
where conditionl

self join

가장 많이 사용되는 방식, inner join과 같은 결과 -> join되는 테이블 간의 공통된 데이터를 가져옴

select col1, col2, ...
from tableA, tableB
where condition (tableA.col1 = tableB.col2);

Concat

여러 문자열을 하나로 합치거나 연결
select concat('string1' , 'string2') from tablename;

예제
select concat('이름: ', name) from celeb

Alias

컬럼이나 테이블 이름에 별칭 생성

ALIAS 문법1- Column
select column as alias from tablename;

예제 1)
select name as '이름' from celeb;

ALIAS 문법2- Table select column1 , column2
from tablename as alias

예제2)
select name as '이름', agency as '소속사' from celeb;

예시3) name과 job_title을 합쳐서 profile 이라는 별칭 만들어서 검색

select concat(name, ' : ', job_title) as profile from celeb;

예제4) snl_show에 출연한 celeb을 기준으로 두 테이블을 조인하여, celeb 테이블을 c, snl_show는 s라는 별칭을 만들어서 출연한 시즌과 에피소드, 이름, 직업을 검색

select s.season, s.episode,c.name, c.job_title
from celeb as c, snlshow as s
where c.name = s.host;

Distinct

검색한 결과의 중복 제거
select distinct column1, column2
from tablename;

예제1) #연예인 소속사 종류를 검색 - 중복 제외

Limit

검색결과를 정렬된 순으로 주어진 숫자만큼 조회
select column1, column2,...
from tablename
where condition
limit number;

profile
최고의 데이터 분석가를 목표로 하는 박세우입니다.

0개의 댓글