-- [] : 선택사항
create table 테이블명(
속성명1 속성타입1 [auto_increment/not null/default],
속성명2 속성타입2...
[constraint 제약조건이름] primary key(속성명),
[constraint 제약조건이름] foreign key(속성명) references 테이블명(속성명) [on delete cascade]
);
-- 새로운 테이블을 생성하면서 기존 테이블을 복사, but 제약조건은 복사되지 않는다
create table 테이블명(select 속성명 from 복사할테이블명);
alter table 테이블명 +
-- 속성 추가
add colunm 속성명 속성타입 [first, after];
-- 속성 수정
modify colunm 속성명 속성타입;
change 원래속성명 바꿀속성명 속성타입;
-- 속성 삭제
drop colunm 속성명;
-- 테이블명 변경
rename 바꾼테이블명;
코드를 입력하세요
select [distisnct] -- 중복제거
order by asc(오름차순, 기본)/desc(내림차순); -- 항상 쿼리문의 마지막에 위치한다
limit 숫자;
select 속성명 from 테이블명 group by (그룹할)속성명 having 조건(=그룹화 할때 적용될 조건)
-- count(), sum(), agv(), ...
-- group by한 항목별 합계의 전체 합계를 구한다
select 속성명, sum(price*amount) 비용 from 테이블명 group by 속성명 with rollup;
CREATE TABLE T1(a INT PRIMARY KEY, b INT, c INT);
INSERT INTO t1 (a,b,c) VALUES (1,2,3) -- 없다면 insert into 문이 실행
ON DUPLICATE KEY UPDATE c=c+1; -- 있다면 c=c+1이 실행
출처 : https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
-- 김경호보다 키가 크거나 같은 사람의 이름과 키를 출력
select name, height from usertbl where name='김경호';
select name, height from usertbl where height > 177;
-- 위의 쿼리를 서브쿼리로 작성시
select name, height from usertbl where
height > (select height from usertbl where name='김경호');
속성명 비교연산자 in/all/any=some/exists(값 or 서브쿼리)
-- 지역이 경남 사람의 키보다 키가 크거나 같은 사람의 이름과 키를 출력
select name, height, addr from usertbl where
height = any (select height from usertbl where addr='경남');
height in (select height from usertbl where addr='경남');
height >= any (select height from usertbl where addr='경남');
height >= some (select height from usertbl where addr='경남');
height >= all (select height from usertbl where addr='경남');
set @변수이름 = 값;
prepare 지정이름 from'사용할 쿼리문'; -- 파라메타 값은 ?로 작성
execute 지정이름 using @변수;
deallocate prepare 지정이름; -- 동적할당 해제
-- while
-- iterate(=continue)
-- leave(=break)
drop procedure if exists 프로시저명;
delimiter $$
create procedure 프로시저명()
begin
declare 변수 변수타입;
set 변수 = 값;
지정이름 : while(조건) do
if(..) then
iterate 지정이름; --> while문의 처음으로 돌아간다
if(..) then
leave 지정이름; --> while문을 벗어난다
end while;
end $$
delimiter ;
now()
current_timestamp()
concat()
auto_increment = 정수; -- auto_increment의 초기값 설정
set @@auto_increment_increment = 정수; -- auto_increment의 증가값 설정
SELECT * FROM Information_schema.table_constraints WHERE table_schema="db명” AND table_name="테이블명";