본문 바로가기
DB/MySQL

MySQL 기본

by Jason95 2020. 12. 27.

출처 : www.boostcourse.org/web326/joinLectures/28762

 

루트 계정으로 접속
mysql -uroot -p
enter password : ********

 

계정 생성
create user 'connectuser'@'%' identified by 'connect123!@#';

특정 계정에게 특정 데이터베이스에 대한 권한 부여
grant all privileges on connectdb.* to connectuser@'%';
flush privileges;

 

특정 계정으로 접속
mysql -h127.0.0.1 -uconnectuser -p connectdb
enter password : connect123!@#

필드(field) = 행(row)과 열(column)의 교차점

 

sql 파일 실행
mysql -uconnectuser -p connectdb < examples.sql

examples.sql 파일 소스를 얻을 수 있는 링크 :

https://github.com/Wordbe/TIL/tree/3b788399c1c3dfc6ad2f58c941fb8eaf91711799/web/05%20DB%20connection/sql

 

<SQL(Structured Query Language)란?>
- SQL은 데이터를 보다 쉽게 검색하고 추가, 삭제, 수정 같은 조작을 할 수 있도록 고안된 컴퓨터 언어입니다.
- 관계형 데이터베이스에서 데이터를 조작하고 쿼리하는 표준 수단입니다.
- DML (Data Manipulation Language) :
 * 데이터를 조작하기 위해 사용합니다.
 * INSERT, UPDATE, DELETE, SELECT 등이 여기에 해당합니다.
- DDL (Data Definition Language) :
 * 데이터베이스의 스키마를 정의하거나 조작하기 위해 사용합니다.
 * CREATE, DROP, ALTER 등이 여기에 해당합니다.
- DCL (Data Control Language) :
 * 데이터를 제어하는 언어입니다.
 * 권한을 관리하고, 테이터의 보안, 무결성 등을 정의합니다.
 * GRANT, REVOKE 등이 여기에 해당합니다.

desc task;
describle task;

select * from department;
select deptno from department;
select deptno, name from department;
select deptno 부서번호, name 부서명 from department;
select empno as 사번, name as 이름, job as 직업 from employee;

함수 사용 ex) concat : 문자열 결합(concatenate)
select concat(empno, '-', deptno) as '사번-부서번호' from employee;

select deptno from employee; 의 결과에서 중복행 제거
select distinct deptno from employee;

select empno, name from employee; 를 정렬
select empno, name from employee order by name; // name을 기준으로 오름차순 정렬
select empno, name from employee order by name asc; // name을 기준으로 오름차순 정렬
select empno, name from employee order by 2 desc; // 2번째 column을 기준으로 내림차순 정렬

select * from employee where job='MANAGER';
select * from employee where deptno in (10, 30); // deptno가 10 또는 30인 row
select * from employee where deptno=10 or deptno=30; // deptno가 10 또는 30인 row
select * from employee where deptno=30 and salary<1500;

LIKE 키워드를 이용한 와일드카드
% : 길이가 0 이상인 문자열
_ : 문자 1개
select * from employee where name like 'A%'; // name이 A로 시작
select * from employee where name like '%A'; // name이 A로 끝
select * from employee where name like '%A%';  // name에 A가 들어감
select * from employee where name like '_A%';  // name의 2번째 글자가 A

select lower(name) from employee; // 소문자로 출력
select substring('Happy Day', 3, 2); // 3번째 index부터 2글자 출력 : mysql에서 첫 index는 0이 아닌 1로 카운트

LPAD RPAD : 빈 칸을 특정 문자로 채우기
select lpad(name, 10, '+') from employee; // 10칸 중 빈 칸을 +로 출력 ex) ++++++KING

그밖에 함수 : TRIM(), ABS(), MOD(), FLOOR(), CEILING(), ROUND(), POW(), GREATEST(), LEAST(), CURDATE(), CURRENT_DATE, CURTIME(), CURRENT_TIME, NOW(), SYSDATE(), CURRENT_TIMESTAMP, DATE_FORMAT(), PERIOD_DIFF()

select deptno, avg(salary), sum(salary) from employee group by deptno;
avg / sum = 그룹함수

insert 시 디폴트 값이 정해진 필드는 생략시 디폴트 값으로 초기화 됨
단, not null 조건이 들어간 필드나 primary key인 필드는 생략 불가
insert into ROLE (role_id, description) values (200, 'CEO');
insert into ROLE (role_id) values (200);
insert into ROLE (description) values ('CEO'); // role_id가 PK이므로 불가

update 시 where 절이 없으면 모든 행이 update 되므로 조심
update role set description='CTO' where role_id=200;

delete 시 where 절이 없으면 모든 행이 delete 되므로 조심
delete from role where role_id=200;

create table employee2(
empno integer not null primary key,
name varchar(10),
job varchar(9),
boss integer,
hiredate varchar(12),
salary decimal(7,2),
comm decimal(7,2),
deptno integer);

alter table employee2
add birthdate varchar(12); // birthdate 행 추가

alter table employee2
drop birthdate; // birthdate 행 삭제

alter table employee2
change deptno dept_no integer; // 컬럼 이름 deptno을 dept_no로 수정

alter table employee2
rename employee3; // 테이블 이름 employee2를 employee3로 수정

drop table employee2; // 테이블 삭제
외래키 제약 조건 존재시
테이블을 생성했던 반대 순서로만 삭제 가능

* 외래키 제약 조건
예를 들어, employee 테이블의 deptno의 후보를
department 테이블의 deptno에 있는 값들로 제약시키는 것
department 테이블이 먼저 만들어지고 나서 employee 테이블이 만들어졌으므로
department 테이블을 삭제하려면 employee 테이블을 먼저 삭제해야 함
drop table department; // 불가 (에러 출력)

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

mysql 패스워드 분실시  (0) 2021.05.05
Mysql insert 문법 오류  (0) 2021.02.16
MySQL을 Ubuntu에 설치하기  (0) 2021.02.01