본문 바로가기

DB

[MySQL] SUB Query

SUB Query

  • Query 안의 Query
  • SELECT 단일 row, 단일 column
select first_name, salary ,(select avg(salary) from employees)
from employees where department_id = 30;

 

  • FROM 다중 row, 다중 column
-- 부서 번호 50, 급여가 6000 이상인 사원
select empno, ename, sal
from (select employee_id as empno, first_name as ename, salary as sal
from employees where department_id = 50) a
where sal >= 6000;

 

  • WHERE 다중 row, 다중 column
-- 평균 급여보다 많이 받는 사원
select * from employees where salary > (select avg(salary) from employees);

 

* 특수 쿼리

  • case
-- substr('hello world', 1, 5) -> hello
-- case
select employee_id, first_name, phone_number, 
	case substr(phone_number, 1, 3)
		when '515' then '서울'
		when '590' then '부산'
		when '650' then '창원'
		else '기타'
	end as 지역
from employees;

→ mysql 에서 인덱스는 0이 아니라 1부터 시작한다.

 

 

'DB' 카테고리의 다른 글

[MySQL] 무결성  (0) 2022.06.20
[MySQL] create, drop, alter / insert, delete, select, update  (0) 2022.06.20
[MySQL] Limit  (0) 2022.06.17
[MySQL] Join  (0) 2022.06.17
[MYSQL] SELECT, WHERE, Group by, having  (0) 2022.06.16