[mysql] select

김민창·2021년 9월 6일
0
post-thumbnail

저장된 DB 예제

  • 테이블명 : country
  • 빈칸은 NULL
CodeNameContinentPopulationisTraveled
KORSouth KoreaAsia48000000YES
JAPJapanAsia100000000YES
CANCanadaNorth America38000000
BRABrazilSouth America210000000
FRAFranceEurope65000000YES
DEUGermanyEurope83000000

조회 기본

select (나타낼 데이터)
from (탐색할 테이블 명)
where (조건);

찾을 데이터와 일치하는지 조회

=

select *
from country
where Code = 'KOR';
  • 프로그래밍 언어와 다르게 == 으로 비교하지 않는다

중복 없이 조회

distinct

select distinct Continent
from country;
  • 중복을 없애고 싶으면 distinct 사용

문장 형식으로 붙여서 조회

concat

select concat(Name, '은 ', Continent, '입니다')
from country;
  • concat 함수를 사용해 준다면 프로그래밍 언어에서 사용하는 보통의 출력방식을 따라간다

오름차순/내림차순 조회

order by

  • order by 다음은 어떤 데이터들을 기준으로 잡고 정렬할지 써준다
  • 오름차순은 생략 가능
select *
from country
order by Population;
  • 내림차순은 desc 추가
select *
from country
order by Population desc;

오름차순/내림차순 중복

  • order by 뒤에 comma로 구분하여 작성
select *
from country
order by Population, Code;

null인지 확인하기

ifnull

select Code, Name, ifnull(isTraveled, 'NO') as '여행경험'
from country;
  • 상위 코드는 isTraveled 의 데이터가 null 이라면 두번째 인자값인 NO 를 출력해라는 뜻
  • ifnull을 사용하지 않는다면, (data) is null 또는 (data) is not null 과 같은 구문을 사용하여 판별해야 한다

and, or 연산

select Code, Name, Population
from country
where Population < 100000000 and isTraveled = 'YES';
  • 일반적인 프로그래밍과 똑같은 역할

한글, 영어 글자수 출력

char_length length

  • length 함수는 문자의 Byte길이를 가져오기 때문에 한글의 정확한 길이를 알 수 없음
  • char_length 는 문자의 Byte수를 계산하지 않고 단순히 몇 개의 문자가 있는지 가져오는 함수

최상위 몇개만 잘라서 출력

limit

select *
from country
order by Population
limit 3;
  • limit를 사용하여 최상위에서부터 갯수를 잘라 출력할 수 있다

limit a,b

select *
from country
limit 0, 2;
  • limit뒤에 comma로 구분하면 첫번째 값 만큼 skip하고, 두번째 값의 만큼을 출력할 것인지 정하는것

문자중 포함하는지 확인

like

select *
from country
where Name like '%Kor%';
  • like로 해당 문자를 포함하고 있는지 확인
  • % : 어떤 값이던 몇개나 있던 상관이 없음
  • _ : 어떤 값이던 한개만 있어야 하고, 여러개 사용 가능
  • data% _data %data %data% 와 같이 사용

in

select *
from country
where Continent in ('Asia', 'Europe');
  • in 뒤에있는 단어들이 포함되어 있는지 확인

마스킹해서 출력하기

  • 양쪽 두개를 제외하고 *로 출력하기
select Code, 
	concat(left(Name, 2), 
	lpad('*', char_length(name) - 4, '*'), 
	right(name, 2)) change
from country;
  • leftright 로 양쪽 두개는 그대로 출력
  • lpad* 를 원하는만큼 채우기
  • concat 을 통해 합쳐서 출력
  • 자리수가 4 이하라면 다른 방법을 사용해야함

조회한값 대체해서 출력하기

case when then end

  • 인구가 1억 이상 이라면 인구 대신 '많다' 출력, 아니라면 '적다' 출력
select Code, Name,
case when Population >= 100000000 then '많다'
else '적다'
end '인구가?'
from country;
  • case 로 시작해서 end 로 종료시켜 주어야 함

조회한값 소수점 자리수 정해서 출력하기

round

select Code, Name, round(Population, 1) '소수점출력'
from country;
  • round 함수를 사용하여 첫번째 파라미터에는 변환할 값, 두번째 파라미터에는 소수점 몇번째 자리까지 나타낼 것인지
  • 두번째 파라미터에 음수가 들어갈수도 있음
profile
개발자 팡이

0개의 댓글