코딩 이야기
mysql 공부정리 본문
728x90
-- 검색조건 지정
select * from sample21;
select no, name from sample21;
select * from sample21 where name='홍길동'; -- 홍길동 검색
select * from sample21 where name<>'홍길동'; -- 홍길동이 아닌것을 검색
select * from sample21 where birthday is null; -- null값을 검색 앞에 is 필수
-- 연산자 검색
select * from sample24;
select * from sample24 where a<>0 and b<>0; -- a와 b가 0이 아닌것을 검색
select * from sample24 where a<>0 or b<>0; -- a가0이아니거나 b가 0이 아닌것을 검색
select * from sample24 where a=1 or a=2 and b=1 or b=2; -- a가1이거나2이면서 b가1이거나2
select * from sample24 where (a=1 or a=2) and (b=1 or b=2); -- 괄호로 우선순위 월래는 and 먼저임
select * from sample24 where not (a<>0 or b<>0);
-- 문자열 검색 (단어를 포함한 문자열 검색)
select * from sample25;
select * from sample25 where text like 'sql%'; -- sql문자열 검색 %는 문자열표시
select * from sample25 where text like '%sql%'; -- %으로 앞뒤 문자열표시
select * from sample25 where text like '%\%%'; -- 이스케이프 문자로%검색
-- 정렬
select * from sample31;
select * from sample31 order by age; -- age 정렬
select * from sample31 order by address; -- address 정렬
select * from sample31 order by age desc; -- 내림차순 정렬
select * from sample31 order by age asc; -- 오름차순 정렬
-- 복수의 열을 지정해 정렬
select * from sample32;
select * from sample32 order by a;
select * from sample32 order by a,b; -- 복수열 지정하기
select * from sample32 order by b,a; -- 복수열 지정하기
select * from sample32 order by a asc, b desc; -- 정렬방법 지정하기
-- mysql 에서 null 값은 가장 작은 값으로 취급해 asc(오름차순)에서는 가장 먼저 desc(내림차순)에서는 가장 나중에 표시합니다.alter
-- 결과 행 제한하기
-- 행수 제한 select 열명 from 테이블명 where 조건식 order by 열명 lemit 행수
select * from sample33;
select * from sample33 limit 3;
-- 정렬한 후 제한하기 (sample33을 정렬 후 limit 3 으로 상위 3건만 취득하기
select * from sample33 order by no desc limit 3;
-- limit를 사용할 수 없는 데이터베이스에서의 행 제한(오라클에서의 행 제한)
-- select * from sample33 where rownum <=3;
-- 오프셋 지정
-- select 열명 from 테이블명 limit 행수 offset 위치 ( 오프셋에 의한 시작위치는 인덱스처럼 -1을 생각하자)
-- 첫 번째 페이지에 표시할 데이터 취득하기
select * from sample33 limit 3 offset 0;
-- 두 번째 페이지에 표시할 데이터 취득하기
select * from sample33 limit 3 offset 3;
-- 수치연산
-- select 구로 연산하기
select * from sample34;
select *, price * quantity from sample34;
-- select 구에서 식에 별명 붙이기
select *, price * quantity as amount from sample34;
-- 주의할점 별명을 문자열로 할경우 ""을 넣어준다 ""는 데이터베이스 객체명 ''는 문자열 상수 또한 이름을 지정할 경우 숫자로 시작하지 않는다.
-- where 구에서 계산, 검색하기
select *, price * quantity as amount from sample34
where price * quantity >= 2000;
-- null값의 연산
-- null로 연산하면 결과는 null이 된다.
-- 예) 1+null = null
-- order by 구에서 연산하기
-- 금액을 내림차순으로 정렬하기
select *, price * quantity as amount from sample34;
-- order by 구에서 금액을 계산하고 내림차순으로 정렬하기
select *, price * quantity as amount from sample34 order by price * quantity desc;
-- order by 구에서 별명을 사용해 정렬하기
select *, price * quantity as amount from sample34 order by amount desc;
-- 함수
-- 함수명(인수1,인수2...)
-- round 함수
-- round로 반올림하기
select * from sample341; -- amount 는 decimal형으로 소수점을 포함하는 수치를 저장하는 자료형
select amount, round(amount) from sample341;
-- 반올림 자릿수 지정
select amount, round(amount,1) from sample341;
-- 10단위 반올림
select amount, round(amount,-2) from sample341;
-- 문자열 연산
-- 데이터베이스마다 문자열 결합의 연산자가 다르다 mysql에서는 concat함수로 문자열을 결합한다.
-- 문자열 결합으로 단위를 연결해 결과 얻기
select * from sample35;
select concat (quantity, unit) from sample35;
-- 문자열로 결합한 결과는 문자열이 된다.
-- substring 함수 (문자열의 일부분을 계산해서 반환해주는 함수)
-- 날짜 앞 4자리 추출
-- sunbsting('20140125001',1,4) -> '2014'
-- 날짜 5째 자리부터 2자리(월) 추출
-- sunbsting('20140125001',5,2) -> '01'
-- trim 함수 (문자열의 앞뒤로 여분의 스페이스가 있을 경우 이를 제거해주는 함수 *문자열 도중에 존재하는 스페이스는 제거되지 않음)
-- trim으로 스페이스 제거하기
-- trim ('abc ') -> 'abc'
-- character_length 함수 (문자열의 길이를 계산해 돌려주는 함수)
-- octet_length 함수(문자열의 길이를 바이드 단위로 계산해 돌려주는 함수)
-- 날짜 연산
-- 시스템 날짜 확인하기
select current_timestamp;
-- 날짜의 덧셈과 뺼셈
-- 날짜를 연산해 시스템 날짜의 1일 후를 검색
select current_date + interval 1 day;
-- current_date = 시스템 날짜확인
-- 날짜형 간의 뺼셈 (datediff('날짜1', '날짜2')
-- case 문으로 데이터 변환
/* case 문
case when 조건식1 then 식1
[when 조건식2 then 식2...]
[else 식3]
end
-- null 값을 0으로 변환하기 */
use sample;
select * from sample37;
select a, case when a is null then 0 else a end "a(null=0)" from sample37;
-- coalesce 여러개의 인수를 지정하여 주어진 인수 가운데 null이 아닌 값에 대해서는 가장먼저 지정된 인수의 값을 반환
select a, coalesce(a,0) from sample37;
-- 또 하나의 case 문 (숫자로 이루어진 코드를 알아보기 더 쉽게 문자열로 변환하고 싶은경우)
-- 성별 코드 변환하기(검색 case)
select a as "코드",
case
when a=1 then '남자'
when a=2 then '여자'
else '미지정'
end as "성별" from sample37;
-- 성별 코드 변환하기(단순 case)
select a as "코드",
case a
when 1 then '남자'
when 2 then '여자'
else '미지정'
end as "성별" from sample37;
-- case를 사용할 경우 주의사항
-- else 생략(else를 생략하면 else null이 되는것에 주의합시다. 되도록 생략하지 않는편 좋음)
-- when에 null 지정하기
-- 단순 case 문에서 when 절에 null 지정하기
select a as "코드",
case a
when 1 then '남자'
when 2 then '여자'
when null then '데이터 없음'
else '미지정'
end as "성별" from sample37;
-- 단순 case 문으로 null 값을 비교할수 없다
728x90
'DB' 카테고리의 다른 글
mysql 공부정리 (2) (0) | 2023.03.14 |
---|---|
mysql 문제풀이 (0) | 2023.03.13 |
서브쿼리 (2) | 2023.03.10 |
키의 종류 (0) | 2023.03.10 |
테이블 제약조건 (0) | 2023.03.09 |
Comments