프로젝션:쿼리를 골라내는 것
select () from :select랑 from이랑 사이에 들어 갈것
기본 서브 쿼리
- where절에 (괄호 하고 쿼리가 하나 더 들어가는것)
select user_id from image_tb where content = '여행사진';
select username
from user_tb
where id = (select user_id from image_tb where content = '여행사진');


집합 할 때 union all 사용 쿼리랑 쿼리를 연결
- 맨 위의 데이터가 컬럼명이 된다, 컬럼의 갯수가 같아야 한다.
- 단점: 사용시 쿼리문이 엄청 길어진다 (기초 코드)
/*사진마다 좋아요 갯수를 몇개 찍혔는지*/
select 1 image_id, count(*) love_count
from love_tb
where image_id = 1
union all
select 2, count(*)
from love_tb
where image_id = 2
union all
select 3, count(*)
from love_tb
where image_id = 3;

미트리=풀스캔보다 빠른 것
엔테이블 기준으로 1테이블을 조회하면
인덱스 스캔을 한다. 인덱스=목차
목차를 보고 찾는다?
목차가 있으면 랜덤 엑세스가 발동한다
인라인 뷰 = 테이블화 시킬 수 있다
하나의 결과만 보고 싶을 때
ex)3번 사진에 몇 명이 좋아요 눌렀는지 보고 싶을 때
n테이블에 행을 줄여 놓고 1테이블과 줄여 놓는게 좋다.
인라인 뷰와 이너 조인을 같이 쓴다.
select *
from
(
select 1 image_id, count(*) love_count
from love_tb
where image_id = 1
union all
select 2, count(*)
from love_tb
where image_id = 2
union all
select 3, count(*)
from love_tb
where image_id = 3
) lo inner join image_tb im on im.id = lo.image_id;

별칭 보고 싶을 때
(from-where-select 순으로 진행 되므로 select에서 my email이 생기는데 생기기 전에 where에서 지정해서 찾을 수 없음)
select id, username, substr(email, 1, 4) my_email
from user_tb
where my_email = 'ssar';
이럴 때 인라인 뷰 를 사용
select *
from (
select id, username, substr(email, 1, 4) my_email
from user_tb
) tb
where my_email = 'ssar';

스칼라 서브쿼리: 프로젝션자리에 서브쿼리를 쓰는 것
커서를 한칸씩 내리면서 프로젝션 한다.
하나의 행이여야 한다. 왜?
select *,
(select count(*) from love_tb where image_id = im.id)
from image_tb im;

프로젝션:select에 해당하는 컬럼을 하나씩 뽑아 내는것
한번
그룹바이

값을 동일하게만든다
세로 연산 하려고
select 보다 group이 먼저 실행된다.
Share article