Database #1

yeolyeol·2024년 9월 9일
0

ssafy12

목록 보기
25/32
post-thumbnail

"MySQL은 DB다."
이 말에 위화감을 느낄 수 있도록 열심히 공부하자.

RDBMS & SQL

관계형(Relational) 데이터베이스 시스템.

  • 테이블 기반(Table based)의 DBMS
    - 데이터를 테이블 단위로 관리.
    하나의 테이블을 여러 개의 컬럼(Column)으로 구성
    • 중복 데이터를 최소화 시킴
      같은 데이터가 여러 컬럼 도는 테이블에 존재 했을 경우,
      데이터를 수정 시 문제가 발생할 가능성이 높아짐. → 정규화

      문제 : 에러 X, 데이터의 일관성이나 데이터 작업에 비효율 적인 처리가 필요함

    • 여러 테이블에 분산되어 있는 데이터를 검색 시 테이블 간의 관계(Join)를 이용하여 필요한 데이터를 검색.

SQL (Strutured Query Language)

  • Database에 있는 정보를 사용할 수 있도록 지원하는 언어.
  • 모든 DBMS에서 사용 가능함.
  • Query는 대소문자를 구분하지 않음
    • Table 이름도 가리지 않음.
      • 단, MySQL 설정에 lower_case_table_names 설정 값에 따라 달라짐.
    • 단, 데이터의 대소문자는 구분함.
    • MySQL은 데이터도 대소문자를 구분하지 않음 (default 설정) :: binary 함수 이용
      • select * from city where name = "dongyeol"
      • select * from city where binary name = "dongyeol"

lower_case_table_names
MySQL의 lower_case_table_names 설정 값에 따라 대소문자 구분할 지 정할 수 있다.

  • window : 기본 값 = 1, 모든 테이블 이름을 소문자로 바꾼다. (== 구분하지 않는다)
  • 리눅스 계열 : 기본 값 = 0, 구분한다.
  • Mac : 기본 값 = 2, window의 1과 같은 설정.

SQL의 종류

  1. DDL (Data Definition Language) : 데이터 정의어
    - 데이터베이스 객체(table, view, index 등)의 구조를 정의.
    - 테이블 생성, 컬럼 추가, 타입 변경, 제약조건 지정, 수정 등

  2. DML (Data Manipulation Language) : 데이터 조작어.
    - Data 조작 기능
    - 테이블의 레코드를 CRUD(Create, Retrieve, Update, Delete)

  3. DCL (Data Control Language) : 데이터 제어어.
    - DB, Table의 접근 권한이나 CRUD 권한을 정의.
    - 특정 사용자에게 테이블의 검색 권한 부여/금지 등

  4. TCL (Transaciton Control Language) : 트랜잭션 제어어
    - transaction : 데이터베이스의 논리적 연산 단위

DML(Select)

일반적으로 SELECT, FROM 절은 필수임

  • 사용할 스키마의 구조

SELECT/FROM

SELECT * | { [ ALL | DISTINCT ] column | expression [ alias ], .... }
FROM table_name;

예제

  1. 기본적인 SELECT
-- 모든 사원의 모든 정보 검색.
SELECT *
FROM employees;

-- 사원이 근무하는 부서의 부서번호 검색.
SELECT department_id
from employees;
-- where department_id is not null;

-- 사원이 근무하는 부서의 부서번호 검색.(중복제거)
SELECT DISTINCT department_id
from employees;

-- 회사에 존재하는 모든 부서.
select department_id
from departments;

-- 모든 사원의 사번, 이름, 급여 검색.
select employee_id, first_name, salary
from employees;
  1. alias(별칭)
    as, "" 없이 사용 가능. 단, 별칭에 띄어쓰기가 존재할 경우에는 ""로 묶어줘야 함.
-- 모든 사원의 사번, 이름, 급여, 급여 * 12 (연봉) 검색.
select employee_id as "사번", first_name "이름", salary 급여, salary * 12 "연   봉"
from employees;

-- 모든 사원의 사번, 이름, 급여, 급여 * 12 (연봉), 커미션, 커미션포함 연봉 검색.
select employee_id as "사번", first_name "이름", salary 급여, salary * 12 "연   봉",
	   commission_pct 커미션, (salary + salary * ifnull(commission_pct, 0)) * 12 "커미션 포함 연봉"
from   employees;
  1. case~when~then(~end)
case
	when 조건1 then 결과1
    when 조건2 then 결과2
    ...
    else 결과N
end 컬럼 명

-- 모든 사원의 사번, 이름, 급여, 급여에 따른 등급표시 검색.
-- 급여에 따른 등급
--   15000 이상 “고액연봉“      
--   8000 이상 “평균연봉”      
--   8000 미만 “저액연봉"
select employee_id, first_name, salary,
	   case
	       when salary >= 15000 then "고액연봉"
           when salary >= 8000  then "평균연봉"
           else "저액연봉"
	   end "연봉등급"
from   employees;
  1. where절 (and, or, not, in, null)
-- 부서번호가 50인 사원중 급여가 7000이상인 사원의
-- 사번, 이름, 급여, 부서번호
select employee_id, first_name, salary, department_id
from   employees
where  department_id = 50
and    salary >= 7000;

-- 근무 부서번호가 50, 60, 70에 근무하는 사원의 사번, 이름, 부서번호
select employee_id, first_name, department_id
from   employees
where  department_id = 50
or     department_id = 60
or     department_id = 70;

-- 근무 부서번호가 50, 60, 70이 아닌 사원의 사번, 이름, 부서번호
select employee_id, first_name, department_id
from   employees
where   department_id != 50
and     department_id <> 60
and not (department_id = 70);

select employee_id, first_name, department_id
from   employees
where not (department_id = 50
or         department_id = 60
or         department_id = 70);

-- 근무 부서번호가 50, 60, 70에 근무하는 사원의 사번, 이름, 부서번호
select employee_id, first_name, department_id
from   employees
where  department_id = 50
or     department_id = 60
or     department_id = 70;
--- or
select employee_id, first_name, department_id
from   employees
where  department_id in (50, 60, 70);

-- 근무 부서번호가 50, 60, 70이 아닌 사원의 사번, 이름, 부서번호 
select employee_id, first_name, department_id
from   employees
where  department_id not in (50, 60, 70);

-- 급여가 6000이상 10000이하인 사원의 사번, 이름, 급여
select employee_id, first_name, salary
from   employees
WHERE  salary BETWEEN 6000 and 10000;

-- 근무 부서가 지정되지 않은(알 수 없는) 사원의 사번, 이름, 부서번호 검색.
select employee_id, first_name, department_id
from   employees
where  department_id is null;

select employee_id, first_name, department_id
from   employees
where  department_id is not null;

-- 커미션을 받는 사원의 사번, 이름, 급여, 커미션
select employee_id, first_name, salary, commission_pct
from   employees
where  commission_pct is not null;
  1. like
-- 이름에 'x'가 들어간 사원의 사번, 이름
select employee_id, first_name
from   employees
where  first_name like '%x%';

-- 이름의 끝에서 3번째 자리에 'x'가 들어간 사원의 사번, 이름
select employee_id, first_name
from   employees
where  first_name like '%x_____';
  1. order by
-- 모든 사원의 사번, 이름, 급여
-- 단 급여순 정렬(내림차순)
select   employee_id, first_name, salary
from     employees
order by salary desc;

select   employee_id, first_name, salary
from     employees
order by 3 desc;

-- 50, 60, 70에 근무하는 사원의 사번, 이름, 부서번호, 급여
-- 단, 부서별 정렬(오름차순) 후 급여순(내림차순) 검색
select   employee_id, first_name, department_id, salary
from     employees
where    department_id in (50, 60, 70)
order by department_id, salary desc;
  1. limit
-- 급여 순 정렬 후 5번째로 높은 급여를 받는 사원의 사번, 이름, 급여
select   employee_id, first_name, salary
from     employees
order by salary desc
limit 1 offset 4;

select   employee_id, first_name, salary
from     employees
order by salary desc
limit 4, 1;

-- 급여 순 정렬 후 1 ~ 5번째로 급여를 많이 받는 사원의 사번, 이름, 급여
select   employee_id, first_name, salary
from     employees
order by salary desc
limit 0, 5;
profile
한 걸음씩 꾸준히

0개의 댓글

관련 채용 정보