본문 바로가기

DB

[MYSQL] SELECT, WHERE, Group by, having

더보기

설치 경로

www.mysql.com  → Download → MySQL Community (GPL) Downloads MySQL Community Server   Go to Download Page  Windows (x86, 32-bit), MSI Installer

 

 

commit;
rollback;

 

select @@autocommit;

 

- 1인 경우 : autocommit이 설정되어있다.

- 0인 경우 : autocommit이 해제되어있다.

workbench를 껐다가 실행한 경우 autocommit 설정을 해야한다.

 

set autocommit = true; -- 설정
set autocommit = false; -- 해제

 

* 테스트 하는 경우 autocommit을 끄는 것이 좋다. 테스트 하는 것도 commit할 필요는 없다.

 

시스템 기본 구조

자료형

JAVA Oracle MySQL
int INTEGER, NUMBER(5) INT, DECIMAL(5, 2) (소수점 두번째자리까지)
double NUMBER DOUBLE
String VARCHAR2 VARCHAR
Date(날짜) DATE DATE

예 :

create table tb_decimal(
	col1 decimal,
    col2 decimal(5),
    col3 decimal(5,2)
);

insert into tb_decimal(col1, col2, col3)
values(1234.5678, 12345.12, 123.456);

실행 결과

 

 

* 테이블 생성

Row(행), Column(열), Record

 

create table 테이블명(
    컬럼명 자료형,
    컬럼명 자료형,
);

 

* 테이블 정보조회

 

select * from INFORMATION_SCHEMA.TABLES 
WHERE TABLE_SCHEMA='Mydb';

 

* CRUD - INSERT, DELETE, SELECT, UPDATE ( Data를 다룰 때 )

* CREATE, DROP, ALTER ( Object를 다룰 때 )

 

 

SELECT

SELECT (값, 컬럼명, 함수, SUB QUERY) FROM (테이블명, SUB QUERY)

 

  • desc : 테이블의 사양을 확인할 수 있음

desc employees 실행결과

  • 임의의 컬럼을 설정할 수 있음
select '이름: ', 20, first_name from employees;

 

  • alias == 별명
select first_name AS "이름", last_name as "성" from employees;
select first_name "이름", last_name "성" from employees;

 

AS와 "는 생략 가능하지만 되도록이면 쓰는 것이 좋다!

 

select concat('이름 : ', last_name, first_name) as '전체이름' from employees;

 

  • concat() 함수를 통해 데이터 합치기가 가능하다.
select first_name, last_name, salary*12 as 연봉 from employees;

 

  • 연산 가능!

 

 

WHERE

  • 대소비교, 판정 : =, !=, <, >, <=, >=, <>
  • IS NULL, IS NOT NULL
  • AND, OR
  • ALL, ANY, IN, EXISTS, BETWEEN( 같은 값 포함 )
  • LIKE
  • ORDER BY, GROUP BY
  • distinct

 

select first_name from employees where first_name >= 'John';

 

- J보다 스펠링이 뒤에 있는 영문자를 가진 사람?

 

select hire_date, first_name from employees where hire_date < date('1991-01-01')

 

- where hire_date < '1991-01-01' 라고 써도 동일한 결과가 나옴.

 

select first_name, last_name, salary from employees 
where salary = ALL(select * from employees where salary = 8000)

select first_name, last_name, salary from employees 
where salary IN(5000, 8000, 10000);

 

- ALL은 AND와 동일. 잘 사용하지는 않음.

 

select first_name, last_name, salary from employees 
where salary = ANY(select salary from employees where job_id = 'IT_PROG');

 

- ANY는 OR와 동일.

 

-- BETWEEN <= AND >=
select first_name, salary from employees where salary >= 3200 and salary <= 9000;
select first_name, salary from employees where salary between 3200 and 9000;

 

- 결과는 동일

 

-- like
select * from employees where first_name like 'G__';
select * from employees where first_name like 'G%';
select * from employees where first_name like '%G%';

 

- '-'  는 1개의 문자를 대신, '%' 는 0개 이상의 문자를 대신함.

 

 select distinct department_id from employees
 order by department_id asc;

 

- distinct 는 중복을 제거함

 

그룹함수

  • COUNT
  • SUM
  • AVG
  • MAX
  • MIN

 

 select COUNT(*), sum(salary), avg(salary), max(salary), min(salary)
 from employees where job_id = 'IT_PROG';

실행 결과

  • ifnull(대상이 되는 컬럼, 출력하고 싶은 값) : 대상이 되는 컬럼이 null인 경우 출력하고 싶은 값을 반환한다. null이 아니라면 대상 컬럼을 반환한다. NullPointException 을 방지하기 위함. 

 

 select first_name, ifnull(commission_pct, 0) from employees

실행 결과

  • truncate() : 소수를 제거하는 함수. 대상 column과 자릿수가 매개변수로 들어간다.

 

 select department_id, sum(salary), max(salary), truncate(avg(salary), 0) 
 from employees group by department_id;

 

  • group by의 조건절 having
    having은 집계함수를 이용하여 조건을 달아야 함
    where은 집계함수를 이용하여 조건을 달 수 없다!

 

 select job_id, sum(salary) from employees group by job_id
 having sum(salary) >= 100000;

 

practice)

 

급여가 5000이상 받는 사원으로 합계를 내서 업무로 그룹화하여

급여의 합계가 20000을 초과하는 업무명과 사원수, 합계, 평균을 구하라

 select job_id, count(*), sum(salary), avg(salary) from employees where salary >= 5000
 group by job_id having sum(salary) > 20000

 

'DB' 카테고리의 다른 글

[MySQL] 무결성  (0) 2022.06.20
[MySQL] create, drop, alter / insert, delete, select, update  (0) 2022.06.20
[MySQL] Limit  (0) 2022.06.17
[MySQL] SUB Query  (0) 2022.06.17
[MySQL] Join  (0) 2022.06.17