Backend/DB

DB(1)-DML/INSERT/UPDATE/DELETE/SELECT

creativeDeveloper! 2022. 9. 26. 16:00
728x90

1. DML(Data manipulation Language)

데이터를 취급하는 구문으로 DML에는 SELECT,INSERT,UPDATE,DELETE가 있다.

모든 초점이 SELECT에 맞춰줘있기 때문에 중요!

새로운 편집기를 열고, web user로 되어있는지, my db인지 두개를 꼭 확인하기!!

DML을 할때는 update rows가 0이 아닌지 확인하기

1) INSERT(데이터 삽입)

insert INTO [테이블명] ([값을 넣을 컬럼명,...])VALUES([컬럼에 넣을 값,...])

desc employees;
 insert into employees (
emp_no
,first_name
,family_name
,email
,mobile
,salary
,commission
,depart_no
)VALUES(
111
,'소라'
,'강'
,'sorah0514@naver.com'
,01023451245
,900000
,'dev001'
,90
);

2) UPDATE(데이터 수정)

update [테이블명] set [컬럼]=[값],...where[조건]

3) DELETE(데이터 삭제)->잘 써야 한다

delete from [테이블명] where [조건]

4) SELECT : 관련해서 알아야 할것도 많고, DB에 영향을 주는것이 많지 않아서 계속 공부해볼수 있음.

select [조회할 칼럼,...] from [테이블명];

10.26일부터 프로젝트 및 강의실 이전

4-1) 산술표현

select FIRST_NAME,FAMILY_NAME,SALARY/10000 from employees;

4-2) 연봉

SALARY에 *12를 해주고 

select FIRST_NAME,FAMILY_NAME,SALARY*12 as 연봉 FROM employees e;

4-3) CONCAT

-- CONCAT()으로 문자열을 합칠 수 있다.
select concat(FAMILY_NAME,FIRST_NAME)as 이름,SALARY from employees; 

이름,월급(700만원)
select 
concat(FAMILY_NAME,FIRST_NAME)as 이름,
concat(truncate(salary/10000,0),'만원') as 월급 
from employees;

*(아스타리크)

* Transaction

- 단계별로 처리가 있지만 하나라도 잘못되면 다시 처음으로 되될려야 한다.

- 두개지만 쪼개지지 않는것.

commit을 했다면 되돌릴수 없음->auto기 때문에 자동으로 저장됨.

-- 2) 특정 조건의 데이터 조회
-- select [컬럼명,...] from [테이블명] where [조건];
select * from employees e where family_name ='김';
select * from employees e where salary >300000;

-- 2-1) AND 조건: 조건을 달수록 조건이 좁아집
select first_NAME,FAMILY_NAME,SALARY from employees e where salary >=1000000 and salary <= 3000000;

-- 2-2) OR 조건 : 조건을 달수록 조건이 넓어짐, 숫자에 싱글쿼터를 하는 것은 문제가 되지 않음

select * from employees e where family_name ='김' or salary ='2000000';

-- 2-3) BETWEEN AND

-- SALARY가 50만원보다 크거나 같고 400만원보다 작거나 같은 사람들의 first_NAME,FAMILY_NAME,SALARY를 구하세요
select first_NAME,FAMILY_NAME,SALARY from employees e where salary >=500000 and salary <= 4000000;

-- 부등호의 경우 특수문자로 인식되는 경우가 있어 이를 최소화하기 위해 사용되기도 한다.
select first_NAME,FAMILY_NAME,SALARY from employees e where salary between 500000 and 4000000;
-- 3) 중복 제거
-- select distinct [중복제거 컬럼] from [테이블명];
-- 이때 단일 컬럼으로 사용하는 것이 가장 효율적이다.
select salary ,family_name from employees e where salary =2000000;
select distinct SALARY,family_name from employees e where salary=2000000;

-- 4) IN(OR 조건과 같은데 더 간결하고 속도도 빠르다.)
-- where FAMILY_NAME='김' OR FAMILY_NAME='이' OR FAMILY_NAME='박';
-- IN은 조건에서 사용하는 컬럼이 모두 같아야 한다.(다양한 컬럼에서는 사용할 수 없다.)
select *from employees e where FAMILY_NAME in ('김','이','박');

-- 5) IN NULL/IN NOT NULL
select *from employees e where commission is null; 
select *from employees e where commission is not null;

-- 6) 문자열 검색 LIKE
-- 일부가 비슷한 내용을 검색 한다.
-- DB 에 부하를 많이 준다.
-- WHERE [컬럼명] LIKE '%[문자열]%';(와일드 카드 사용->아무거나 들어와도 된다)

-- ze% =>ze로 시작하는...
-- %com =>com으로 끝나는...
-- %se% => se를 포함하는...
-- %s%e% => s와 e를 포함하는...(거의 검색이 되지않음)

select email from employees e where email like 'ze%';
select email from employees e where email like '%com';
select email from employees e where email like '%se%';
select email from employees e where email like '%s%e%';

-- 7) 정렬(order by)
-- 특정 컬럼을 기준으로 정렬
-- ASC(오름차순=생략가능,낮은수부터) | DESC(내림차순,높은순부터)
-- SELECT[컬럼명] FROM [테이블명] ORDER BY [컬럼명] [ASC|DESC]
select * from employees e order by salary;
select * from employees e order by salary desc;
-- 별칭으로도 정렬이 가능
select FAMILY_NAME,FIRST_NAME,SALARY*12 as 연봉 from employees e order by 연봉 desc;
-- 다중 정렬
select * from employees e order by first_name, salary desc;
-- SALARY가 200만원 이상인 사람을 FAMILY_NAME 오름차순으로 정렬해서 보여주세요
-- 정렬은 항상 마지막에 해야 한다.
-- ORDER BY는 데이터 수집이 끝난뒤 이루어짐
select *from employees e where salary >=2000000 order by family_name;

-- 8) GROUP BY
-- 데이터를 그루핑해서 결과를 가져오는 경우
-- SELECT[컬럼명,...] from [테이블명] GROP BY [그룹핑할 컬럼] ->depart_no를 기준으로 묶는것
select depart_no,sum(salary) from employees e group by depart_no;-- 팀별 급여 합계
select depart_no,avg(salary) from employees e group by depart_no;-- 팀별 급여 평균
select depart_no,count(*) from employees e group by depart_no; -- 팀별 인원 수

-- select 뒤에 나오는 컬럼은 group by의 컬럼 또는 집계 함수여야 한다.
-- 각 그룹의 첫값이 나온다.(에러 방지용으로 제공...)
--select * from employees e2 where depart_no ='dev001';
select depart_no,salary from employees e group by depart_no;
-- group by는 특정 컬럼을 묶어서 하나로 가져와야 하는데 salary는 여러개이다.
-- 그래서 가져오고 싶다면 하나로 표현할 수 있는 집계(sum,avg)를 해야한다.

-- depart_no를 기준으로 묶어서 depart_no,salary,commission을 모두 가져와보자
select 
depart_no,sum(salary)as 급여합계,avg(commission) as 인센평균
from employees e group by depart_no;


-- 9) having
-- group by 결과로부터 특정 조건을 추출할 경우 사용
select 
depart_no,sum(salary)as 급여합계,avg(commission) as 인센평균
from employees e group by depart_no order by 급여합계 desc;

-- having은 일반 select문의 where라고 생각하면 된다.
select 
depart_no,sum(salary)as 급여합계,avg(commission) as 인센평균
from employees e group by depart_no having 급여합계>10000000
order by 급여합계 desc;

-- having 절에는 별칭을 쓸수 없다(몇몇 DB에서는 허용->마리아 DB)
select 
depart_no,sum(salary)as 급여합계,avg(commission) as 인센평균
from employees e group by depart_no having SUM(salary)>10000000
order by 급여합계 desc;



 

728x90

'Backend > DB' 카테고리의 다른 글

DB(3)-ERD 관계도/SUB QUERY/JOIN  (0) 2022.09.27
DB(2)- Transaction/Constraint  (0) 2022.09.26