스마트팩토리부트캠피2기 회고 sql

Chaedonghyun·2023년 4월 21일

MySQL
가장 널리 사용되고 있는 관계형 데이터베이스 관리 시스템(RDBMS)이다. 오픈소스 이며 윈도우,Mac,리눅스 등 다양한 운영체제에서 사용 가능하다.

데이터베이스 구축 단계

데이터베이스만들기->데이블 만들기->데이터 입력/수정/삭제->데이터 조회

DDL(Data Definition Language)

데이터 정의어

create문

데이터베이스와 테이블을 생성하는 명령어이다.
ex) create database 이름 default character set utf8 default collate utf8_general_ci;

create table customer( -- 테이블 생성
custid varchar(10) not null primary key, -- 기본키 설정 null값이 없게
custname varchar(10) not null,
addr varchar(10) not null,
phone char(11),
birth date
);

create table orders(
orderid int not null primary key,-- 기본키 설정 null값이 없게
custid varchar(10) not null,
prodname varchar(6) not null,
price int not null,
amount smallint not null,
foreign key(custid) references customer(custid) on update cascade on delete cascade -- 참조키를 설정해서 custid을 customer의 custid를 참조 한다. 업데이트나 수정 허용
);

테이블 삭제문 drop table 테이블명;

alter문

alter table 테이블명 add 속성이름 속성데이터 타입 ; -- 기존속성 추가
alter table customer add email varchar(20);

alter table 테이블명 drop column 속성이름; --기존속성 삭제
alter table customer drop column email;

alter table 테이블명 modify 속성이름 데이터타입; --기존속성 수정
alter table customer modify phone varchar(11);

alter table 테이블명 rename 속성이름 to 바꿀이름; --속성 이름 수정
alter table customer rename cutid to userid;

DML(Data Manipulation Language)

데이터 베이스의 내부 데이터를 관리하기 위한 언어

1.insert문

테이블에 새로운 투플을 추가
insert into 테이블명 (필드1,필드2,필드3...) values(값1,값2,값3,...);
insert into 테이블명 values(값1,값2,값3..); ->필드를 명시하지 않는 경우 테이블의 모든 칼럼에 값을 순서대로 추가해야 한다.

2.update문

테이블에서 특정 속성 값 수정
update 테이블명 set 필드1=값1 where 필드2=조건2;

3.delete문

테이블의 기존 투플을 삭제
delete from 테이블명 where 필드1=값1;

4.select문(★★★)

데이터를 검색하는 기본 문장
select 속성이름 from 테이블명 where 검색조건

where조건(부정연산자)
!=같지 않다

where조건(범위,집합,패턴)
between a and b :a와 b의 값 사이에 있으면 참
in(list):리스트에 있는 값 중에서 어느 하나라도 일치하면 참
like(비교문자열):비교 문자열과 형태가 일치하면 사용(%, )사용
%:0개 이상의 어떤 문자
: 1개의 단일문자

where조건(복합조건)
and- 앞에 있는 조건과 뒤에 오는 조건이 참(TRUE)가 되면 결과도 참(TRUE)
or-앞에 있는 조건과 뒤에 오는 조건중 하나라도 참(TRUE)면 결과는 참(TRUE)
not-뒤에 오는 조건과 반대되는 결과를 돌려준다

oreder by

결과가 출력되는 순서 조절 where절과 함께 사용 가능(where절 뒤에 나와야 함)
select 속성이름 from 테이블이름 where 검색조건 order by 속성이름
asc:오름차순(기본값)
desc:내림차순

DISTINCT

중복된 테이터 제거
select [distinct] 속성이름 from 테이블이름 where 검색조건 order by 속성이름

LIMIT

출력 개수 제한
select [distinct] 속성이름 from 테이블이름 where 검색조건 [order by] 속성이름 [limit 개수]

집계함수

sum() 합계
avg() 평균
max() 최대값
min() 최소값
count() 행 개수
count(distinct) 중복 제외한 개수

GROUP BY

속성이름끼리 그룹으로 묶는 역할
having
group by절의 결과를 나타내는 그룹을 제한
select [distinct] 속성이름 from 테이블이름 where 검색조건[group by]속성이름 [having] 조건식 [order by 속성이름][limit 개수]

profile
SMF 일기

0개의 댓글