서브 쿼리

서브 쿼리 종류 3가지
Feb 02, 2024
서브 쿼리
select 쿼리안의 select 쿼리 서브쿼리라 한다.

서브 쿼리 3가지 종류

1. 서브 쿼리

💡
where절에 들어가는 서브쿼리
```select user_id from image_tb where content = ‘여행사진’; +
select username from user_tb where id = 1;
= select username from user_tb where id = (select user_id from image_tb where content = ‘여행사진’);
 
select max(id) from user_tb; +
select username from user_tb where id = 3;
= select username from user_tb where id = (select max(id) from user_tb);

2. inline view

💡
from절에 들어가는 서브쿼리 테이블화 시킬 수 있음 → join이 매우 편해짐
select image_id,count() love_count from love_tb where image_id = 1 union all select image_id,count() from love_tb where image_id = 2 union all select image_id,count(*) from love_tb where image_id = 3;
→ join
select * from ( select image_id,count(*) love_count from love_tb where image_id = 1 union all select image_id,count(*) from love_tb where image_id = 2 union all select image_id,count(*) from love_tb where image_id = 3 ) mylove_tb inner join image_tb im on im.id = mylove_tb.image_id;

3. scala 서브 쿼리

💡
프로젝션 절에 select를 한번 더 쓰는 것 scala 서브 쿼리는 결과가 반드시 하나의 행이어야 한다.
select *, (select count(*) from love_tb where image_id = im.id) from image_tb im;
 
Share article
RSSPowered by inblog