강좌2번째(5~6차시)
JOIN에 대하여
select * from city join country on city.CountryCode=country.Code;
select city.CountryCode, GNP from city join country on city.CountryCode=country.Code;
--GNP는 country 테이블에 있으므로 그냥 GNP라 쓰면 됨
-- JOIN의 방향이 중요하다. city 테이블에서 -> country 테이블을 JOIN하는 것.. 좌에서 우로
JOIN의 종류
1) INNER JOIN : JOIN시 NULL값을 허용하지 않음(NULL값을 가진 레코드는 JOIN결과에서 빠짐) -> 일반적인 JOIN임
2) LEFT JOIN : JOIN시 JOIN의 왼쪽 테이블의 NULL값을 포함해서 표시
ex) 직원테이블, 부서테이블이 있을때 만약 부서가 없는 직원, 직원이 한명도 없는 부서의 경우 INNER JOIN에서는 모두 제외된다.
A join B에서 A에는 있는데 B에는 없는 경우, 즉 B가 NULL일때 허용하고 싶으면? -> 즉 부서가 없는 직원을 보이게 하고 싶으면 LEFT JOIN을 써야함
반대의 경우 A join B에서 B에는 있는데 A가 없는 경우.. 즉 직원이 아무도 없는 부서는 표시해야한다? -> RIGHT JOIN
3) RIGHT JOIN : 방금 설명했음
4) FULL JOIN : LEFT, RIGHT JOIN 모두 살리는거(근데 MySQL에서는 지원하지 않음)
하고 싶으면 LEFT RIGHT를 UNION 해야함.
실습)
1. city 테이블에는 있는데 country테이블의 code에는 없는 거 찾기
select count(*) from city where CountryCode is NULL;
--> 일단 이렇게 하니 0건 나옴
select count(*) from city join country on city.CountryCode = country.Code;
select count(*) from city left join country on city.CountryCode = country.Code;
--> 둘다 4079건 나옴.. 즉 city의 CountryCode값은 모두 country테이블에 들어있다는 거.. 즉 나라없는 도시는 없다는거
select count(*) from city right join country on city.CountryCode = country.Code; and city.CountryCode is null;
--> 이거는 4086건임.. 즉 국가는 존재하는데 도시를 하나도 안가지고 있는 국가가 있다는거
숙제) 어느 국가가 도시를 하나도 안가지고 있는지 찾아보자
select country.Name from city right join country on city.CountryCode = country.Code where city.Countrycode is null;
ALIAS (별명) 사용하기
select city.CountryCode as Abbr, country.Name as FullName
from city join country on city.CountryCode=country.Code
where city.CountryCode='KOR'
VIEW : sql의 결과값을 임시테이블로 저장해서 나중에 다른 용도로 사용할 수 있는 오브젝트, 임시테이블로 이해하자
-> CREATE VIEW 뷰이름 AS SELECT ~
create view sampleView as
(select city.CountryCode as Abbr, country.Name as FullName from city join country on city.CountryCode=country.code where city.CountryCode='KOR');
VIEW 확인 : select * from sampleView;
VIEW 삭제하기 : drop view sampleView;
6장)
쿼리결과를 새 테이블로 만들기
CREATE TABLE 테이블명 SELCT * FROM 테이블명
-> create table city_new select * from city where CountryCode='KOR';
INSERT INTO 테이블명 SELECT * FROM 테이블명 WHERE 조건절~
참고)
desc city; --> 이렇게 하면 테이블 스키마를 보여주는데
show create table city; --> 이렇게 하면 create 문을 보여준다.
CASE .. WHEN .. END 사용법
CASE WHEN 조건값1 THEN ...
WHEN 조건값2 THEN ...
ELSE ...
END
select case when length(name) > 3 then upper(mid(name, 1, 3))
when ength(name) <= 3 upper(name)
end, population from city;
--> 도시이름이 3자가 넘느냐 3자리이하냐에 따라 자르고 보여주냐, 그냥 보여주냐 처리