AWS/MySQL
MySQL 날짜처리 day(),dayname(),now(),date_format(),date_add( , interval ), on update now()
leopard4
2022. 12. 7. 17:20
-- 날짜 관련 처리하는 방법 --
insert into people2 (name, birthdate, birthtime, birthdt)
values ('Mike', '1990-11-11', '10:07:35','1990-11-11 10:07:35'),
('Larry', '1972-12-25', '04:10:42', '1972-12-25 04:10:42');
-- 날짜(일) 정보만 가져오기
select name, day(birthdate)
from people2;
-- 요일 정보만 가져오기
select name, dayname(birthdate)
from people2;
-- 1=Sunday, 2=Monday, 3=Tuesday '''
select name, dayofweek(birthdate)
from people2;
select name, dayofmonth(birthdate)
from people2;
-- 365기준 일수
select name, dayofyear(birthdate)
from people2;
-- 월정보만 나온다.
select name, month(birthdate)
from people2;
-- 시 , 분 , 초
select name, hour(birthtime), minute(birthdt), second(birthdt)
from people2;
-- db에 저장된 시간형식의 데이터를
-- 사람이 보기 편한 데이터로 바꾸는 방법
select date_format(birthdt, '%Y년 %m월 %d일, %h시')
from people2;
-- 현재 시간을 가져오고 싶을때, now() 함수를 사용.
select now();
-- 현재 년월일 만 가져오고 싶을때, curdate()
select curdate();
-- 시분초 만 가져오고 싶을때, curtime()
select curtime();
-- 날짜의 차이를 구하는 방법 datediff()
-- birthdt 와 현재날짜의 차이를 구하자.
select datediff(now(), birthdt )
from people2;
-- 날짜를 하루 증가시킨다.
select birthdt, date_add(birthdt, interval 1 day)
from people2 ;
-- 3달 증가시킨다
select birthdt, date_add(birthdt, interval 3 month)
from people2 ;
select birthdt, date_add(birthdt, interval 7 day)
from people2 ;
select birthdt, date_add(birthdt, interval 7 hour)
from people2 ;
-- add와 반대 개념 sub
select birthdt, date_sub(birthdt, interval 7 hour)
from people2 ;
-- 그냥해도 된다. + = add , - = sub
select birthdt, birthdt + interval 7 hour
from people2;
-- 이런거도 된다.
select birthdt, birthdt - interval 9 day + interval 3 hour
from people2;
-- MySQL 에서 날짜시간을 저장하는 데이터 타입은
-- date, time, datetime, timestamp(기준점으로 부터 정수로 나온다)
-- 댓글 날짜 최신화의 베이스
-- 테이블 생성 디폴트 값에 now() on update now()를 하면 최신날짜로 덮어쓰기가 된다.
-- - comments 테이블 생성
-- - id 컬럼
-- - content 컬럼
-- - created_at 컬럼
insert into comments ( content, created_at)
values ('좋아요', now());
select *
from comments;
insert into comments ( content, created_at)
values ('저는 싫어요.',now());
-- 테이블수정에서 디폴트값으로 now()를 매번 쓸 필요가 없다.
insert into comments ( content)
values ('대박 입니다.');
-- 댓글 수정할때에도 수정한 시간을 저장하도록 테이블 수정!
-- updated_at 컬럼을 만듭니다.
delete from comments;
select *
from comments;
insert into comments ( content)
values ('좋아요');
update comments
set content = '싫어요'
where id = 6;
-- on update now()
update comments
set content = '굿'
where id = 6;