728x90
목차
1. 서브쿼리
2. 집합연산

 

1. 서브쿼리

  • 쿼리문 내에 또 다른 쿼리문이 있는 형태
  • 서브쿼리는 메인쿼리에 포함되는 관게
  • 사용 가능한 위치
  • 종류

단일행 서브쿼리(Single Row SubQuery)

  • 결과가 레코드 하나인 서브쿼리
  • 일반 연산자(=, >, <, …) 사용
select count(*) from city where CountryCode =(select Code from country where Name=‘South Korea’);
select Name, Population from city where Population > (select avg(Population) from city where CountryCode=‘KOR’) order by Population desc;

 

다중행 서브쿼리(Multi Row SubQuery)

  • 결과가 레코드 여러 개인 서브쿼리
  • 다중행 연산자 (IN, ALL, ANY, EXISTS) 사용
  • ALL
  • ANY
  • IN/EXISTS
select CountryCode, count(*) from city where CountryCode IN(select Code from country where Name in (’South Korea’, ‘China’, ‘Japan’)) group by CountryCode;
select Name, CountryCode, Population from city where (Name, CountryCode) in (select Name, CountryCode from city where Population > 500000);
select Name, CountryCode, Population from city where Population > ALL (select Population from city where countryCode=‘KOR’);
select Name, min(Population) from city where Population > ANY(select Population from city where CountryCode=‘KOR’);
select count(*) from city where EXISTS (select * from city where CountryCode=‘KOR’);

 

다중컬럼 서브쿼리(Multi Column SubQuery)

  • 결과가 컬럼 여러 개인 서브쿼리

 

2. 집합연산

  • 각종 집합연산 지원
  • 합집합(UNION), 교집합(INTERSECT), 차집합(MINUS)
  • MySQL은 INTERSECT/MINUS는 지원하지 않음
select * from city where CountryCode=‘KOR’ UNION select * from city where CountryCode=‘CHN’;
select CountryCode from city where CountryCode=‘KOR’ UNION ALL select CountryCode from city where CountryCode=‘CHN’;
728x90

+ Recent posts