DBMS (MySQL)

[DBMS] order by, limit, distinct, group by, 서브쿼리, 다중조건문

(งᐛ)ว 2023. 7. 30. 23:26
728x90

[order by]

select * from 테이블명 order by 컬럼명 desc/asc;

select문 사용 시 테이블에 입력된 순서대로 출력되는 것이 기본

내림차순(desc), 오름차순(asc) 정렬 필요할 때 사용

 

기본사용

select * from city order by population desc;

 

컬럼 합산 사용 후 별명부여하고 오름차순 정렬

select id + population as total from city order by total asc;

 

컬럼 우선순위 정렬

select from countrylanguage order by 1;   **오름차순 asc는 생략가능

select * from countrylanguage order by 1 desc;

 

여러컬럼 사용

①7번째 컬럼을 오름차순으로 우선정렬하고  첫번째 컬럼을 내림차순으로 정렬

select from country order by 7,1 desc;

7번째 컬럼을 내림차순으로 우선정렬하고  첫번째 컬럼을 오름차순으로 정렬

select from country order by 7 desc, 1 asc;

 


[limit]

select문 결과 레코드 수를 지정

 

select * from city limit 5;   *5개만 출력

select * from city limit 2,3;   *3번째부터 3개만 출력(컴퓨터숫자는 0부터 시작. 첫번째 데이터는 0번째 데이터. 0,1,2->3번째)


[distinct]

결과 값 중복 제거 구문

select distinct * from 테이블명;

select count(*) from 테이블명;   **결과 값의 개수 확인

 

select continent from country;

select distinct continent from country;


[group by]

select 컬럼명1, 집계함수(컬럼명2) from 테이블명 where 조건

group by 컬럼명1 having 조건 order by 컬럼명1 desc/asc;

 

특정 컬럼을 기준으로 count, sum, avg 등 집계함수 사용하여 데이터 추출 시 사용

기준 컬럼 여러 개 지정가능, having구문 함께 사용하여 where처럼 조건부여가능 

 

컬럼명1은 피벗테이블의 행레이블같은 기준역할, 컬럼명2는 계산 필요한 속성 (≒피벗 값필드)

집계함수 적용하지 않은 속성은 where조건, 집계함수 적용한 속성은 having조건 적용

ex. where name like('A%')having population > 10000 

 

자동적으로 order by 정렬되지만 명시적으로 입력하는 것이 좋음 

평균(avg) 사용시 round 등 수학함수 함께 응용가능


대륙별 인구수 총합 확인 
select continent, sum(population) from country group by continent;

 


[서브쿼리]

SQL문에 또다른 SQL문을 삽입해 검색에 이용

여러번 DB 접속이 필요한 상황을 한번으로 줄이기 때문에 속도↑

단일 행 서브쿼리(서브쿼리가 오직 한 건의 결과만을 반환)의 비교연산 : =,>,< 등

다중 행 서브쿼리(서브쿼리가 두 건 이상의 결과를 반환)의 비교연산 : in, any, all, exists 등  

 

select name, headofstate

from country

where code=(select 'SWE');

select name, headofstate, population 

from country

where population=(select max(population) from country);

 

 

단일 행 서브쿼리

select * from city

where countrycode=(

select countrycode from city where name='Seoul');   *결과가 한 개(KOR)로 단일 행   

 

select * from city

where countrycode='KOR';

 

위의 두 쿼리 결과는 동일함

 

select * from city

where countrycode=(

select countrycode from city where name='Washington');  *결과가 한 개(USA)로 단일 행   

 

select * from city

where countrycode='USA';

 

위의 두 쿼리 결과는 동일함

 

다중 행 서브쿼리

any연산 : 전체 값 중 하나라도 만족하면 참 
all연산 : 모든 값 만족해야 참 

 

select from city

where population > any(

select population from city where district='New York');   *결과(뉴욕 주 인구 확인된 도시)가 6개로 다중 행   

 

any : 전체 도시 목록에서 뉴욕 주 도시(6개) 인구 중 한곳이라도 넘기면 출력

결과는 3782개의 도시가 출력됨 

 

select from city

where population > all(

select population from city where district='New York');   *결과(뉴욕 주 인구 확인된 도시)가 6개로 다중 행   

 

all : 전체 도시 목록에서 뉴욕 주 도시(6개) 인구를 모두 넘기면 출력 

결과는 9개의 도시가 출력됨 


[다중조건문]

if조건을 여러 개 사용 

select if(조건1, 참일때반환값, if(조건2, 참일때반환값, 거짓일때반환값)) from 테이블명;

조건1이 거짓일 때, 조건2로 한번 더 참 거짓을 나누는 조건 사용 (조건2는 조건1의 거짓)

 

기본if문

select if(population > 1000, '1000보다큼', '1000보다작음') as rs from city; 

다중조건문

select if(population > 1000'1000보다큼',

if(population > 500, '500보다큼', '500보다작음')) as rs from city;

->인구가 1000보다 작을때 500을 기준으로 한번 더 참 거짓을 나누는 조건

 

select if(percentage > 5,'5>',
if(percentage > 2.5,'2.5>','2.5<')) as rs from countrylanguage;

 

 

 

 

728x90