[MySQL] 자료형별 table 생성 및 조회

sua_ahn·2023년 1월 9일
0

MySQL

목록 보기
2/6
post-thumbnail

table을 저장할 DB 구축!

-- db 조회
show databases;

-- db 생성
create database mydb;

-- db 삭제
drop database mydb; 

-- 사용할 db 선택
use mydb;

자료형별로 table을 만들고 조회해보자!

create table, insert into, select 구문 사용

1. 문자

  • 고정형 문자열 char(M) → M개의 글자를 저장할 공간 확보
  • 가변형 문자열 varchar(M) → 최대 M개의 글자 저장 가능
-- 테이블 생성 (컬럼 2개)
create table tb_string(
	col1 char(10),
    col2 varchar(20)
);

-- 데이터 추가 (필드 2개)
insert into tb_string(col1, col2)
values (
	'abc', 'ABC'
    ),(
    'abcdef', 'ABCDEF'
);

-- 테이블 조회 (모든 컬럼)
select * from tb_string



2. 숫자

  • 정수 int, decimal
  • 실수 decimal(M, D)
    → M은 전체 자릿수의 최댓값(precision), D는 소수점 뒤 최대 자릿수(scale)
-- 테이블 생성 (컬럼
create table tb_numeric(
	col1 int,
    col2 decimal, 
    col3 decimal(5),
    col4 decimal(5, 2)
);

-- 데이터 추가
insert into tb_numeric
values (
	1000,
	12345.67, 
    12345.67, 
    123.456
);

-- 테이블 조회 (모든 컬럼)
select * from tb_numeric;

-- 출력
+------+-------+-------+--------+
| col1 | col2  | col3  | col4   |
+------+-------+-------+--------+
| 1000 | 12346 | 12346 | 123.46 |



3. 날짜

  • 날짜 date
  • 날짜 및 시각 datetime
    → 범위: 1000-01-01 00:00:00 ~ 9999-12-31 23:59:59
  • 날짜 및 시각 timestamp
    → 범위: 1970-01-01 00:00:00 ~ 2037-01-19 03:14:07
  • 시간 time
  • 연도 year
-- 테이블 생성
create table tb_date(
	col1 date,
    col2 datetime,
    col3 timestamp,
    col4 timestamp default now(),
    col5 time
);

-- 데이터 추가
insert into tb_date
values(now(), now(), now(), now(), now());

-- 데이터 추가 (col3는 Null)
insert into tb_date(col1, col2, col5)
values (
	'1000-01-01', 
    '9999-12-31 23:59:59', 
    '838:59:59'
);

-- 테이블 조회
select * from tb_date;
profile
해보자구

0개의 댓글