Cloud System Engineer

sql 기본 본문

mysql/MySQL

sql 기본

클라우드 엔지니어 2021. 2. 6. 17:58

create table testtbl1 (id int , username char(3), age int);
insert into testtbl1 values (1 , '홍길동',28);

-- id 와 이름만 입력하겟다면 다음과 같은테이블

 

insert into testtbl1(id,username) values(2, '상만이'); -- age 를 생각하면 null 값이 들어간다.

 

-- 열의 순서를 바꿔서 입력하고 싶을 때는 꼭 열이름을 입력할 순서에 맞춰 나열해 줘야 한다.
insert into testtbl1(username,age,id) values('상식이',22,3);

 

select * from testtbl1

 testtbl1;

 

 

 

-- 자동으로 증가되는 auto_increment 
create table testtbl2 (id int auto_increment primary key, username char(3),age int);
select*from testtbl2; -- 자동으로 숫자가 증가됨
insert into testtbl2 values(null,'지민',20);
insert into testtbl2 values(null,'정민',22);
insert into testtbl2 values(null,'수민',30);

 

 

 

 

create table testtbl3 (id int auto_increment primary key, username char(3),age int);
alter table testtbl3 auto_increment=1000;  -- 초기값은 1000으로함
set @@auto_increment_increment=3; -- 증가 값은 3으로 한다.
insert into testtbl3 values(null,'지민',20);
insert into testtbl3 values(null,'정민',22);
insert into testtbl3 values(null,'수민',30);
select*from testtbl3; -- 1000부터 시작해서 증가하는값은 3이다.

 

 

-- 대량의 샘플 데이터 생성하는방법
create table testtbl4 (id int,Fname varchar(50),Lname varchar(50));
insert into testtbl4 select emp_no,first_name,last_name from employees.employees ;
select * from testtbl4;

 

 

-- 데이터수정 
update testtbl4
set Lname='없음' where Fname='kyoichi'; -- where 절을 생략하면 테이블전체 행이 변경된다.
select * from testtbl4 where Fname='kyoichi'; -- 결과

 

 

-- 만약 전체 행을 변경하고 싶을때, ex) 현재 단가가 모두 1.5 배가 인상되었다.
update buytbl set price=price*1.5;
select *from buytbl;

 

-- 데이터의 삭제 delete from
delete from testtbl4 where Fname='Aamer';  
select *from testtbl4 where Fname='Aamer'; 

-- 상위 5건만 삭제하겠다면
delete from testtbl4 where Fname='kyoichi'limit 5;

 

-- 대용량 테이블 삭제 

create table bigtbl1(select*from employees.employees);
create table bigtbl2(select*from employees.employees);
create table bigtbl3(select*from employees.employees);
select *from bigtbl1;
select *from bigtbl2;
select *from bigtbl3;

 

delete from bigtbl1; -- 30만건을 삭제함

 

drop table bigtbl2; -- 테이블 자체를 삭제함

 

 

 

 

truncate table bigtbl3; -- 테이블의 구조는 남아있지만 내용은삭제됨

 

 

 

-- 조건부 데이터 입력

select userid as'사용자',sum(price*amount) as '총구매액' from buytbl group by userid;

 

 

-- 비 재귀적 cte
with abc(userid,total) as (select userid,sum(price*amount) from buytbl group by userid)

 

with문은  abc는 위에사용자,총구매액을 표전체를 테이블로 만들겠다는 뜻이다.

 

select*from abc order by total DESC;

테이블 선택을 abc로하고  총구매액을 DESC로 하겠다.

 

-- 결론 복잡한걸  단순화 시킴

-- with 절 cte를 표한 하기위한 구문이다.  cte는 기존의 뷰, 테이블 ,임시테이블 등으로 사용되던 것을 대신할수있다.
-- 재귀적과 비재귀적 두가지가 있다. 

 

'mysql > MySQL' 카테고리의 다른 글

sql 고급  (0) 2021.02.14
Group by , having 절  (0) 2021.02.01
SQL기본 - WHERE 절  (0) 2021.01.29
select 문  (0) 2021.01.29
사용자 관리  (0) 2021.01.28