https://www.youtube.com/watch?v=HXV3zeQKqGY
What Is Database?
DBMS(database management system)
database 관리하는 software
C.R.U.D
Ctreate
Read
Update
Delete
relational database(SQL)/ non-relational database(noSQL)
relational database- table 형태
non-relational database: 정해진 형태 없음. json같은 거라던가.. xml…
RDBMS
DBMS for Relational database
SQL
Structured Query language
non relational database는
Document (ex: json)
graph
key-value hash
etc
Tables & Keys
table
primary key
primary key: unique한 정보
surrogate key: 현실 정보와 별 관련 없는 prymary key
natural key: 현실적 목적이 있는 prymary key
foreign key: 어떤 primary key의 row를 다른 table로 연결시켜주는 key 혹은 self로도 연결할 수도 있음. 막 특별한 건 아니고 걍 id 적어놓는 곳인 듯.
composite key: 2개의 attributes가 필요한 primary key.첫번째 attribute나 두번째 attribute로만 unique하게 identify되지 않을 때 필요함. 두개를 합쳐서 primary key로 쓰는 거지.
SQL basics
SQL 쓰는 데이터베이스는 많은데 다 똑같지는 않음. 그래도 기본적인건 다 같을거야.
SQL은 4가지가 합쳐진거
DQL (data query language)
정보 가져오는 거
DDL (data definition language)
schema 정의. database의 layout 같은 거. column에 어떤 정보가 들어갈건지, 데이터 타입은 뭔지 등
DCL (data control language)
permission관련
DML (data manipulation language)
inserting, upadting, deleting
SQL General
SQL문 (SQL reserve word) 다 대문자로 쓰는건 그냥 관례고, 소문자로 써도 사실 상관은 없음.
모든 SQL문은 semicolon(;)으로 끝남.
single quotation mark랑 double quotation mark랑 좀 사용하응 곳이 차이가 있음.
single은 string할 떄 사용하고, double은 database identifier에 쓰인다고 함. (link)
Creating Tables
Basic Data Types
INT : whole numbers
DECIMAL(m,n) : decimal numbers - exact value. 소숫점 위로 m자리, 아래로 n자리
VARCHAR(n) : string of text of length n
BLOB : Binary large object, stores large data. 이미지나 파일 저장할 때 씀.
DATE : YYYY-MM-DD
TIMESTAMP : YYYY-MM-DD HH:MM:SS -used for recording
이거말고도 몇 개 더 있다고 함.
NVARCHAR(n) : 길이n의 Unicode를 지원함.
Create Table
CREATE TABLE tablename (
row_id INT PRYMARY KEY,
attribute1 DECIMAL(3,10),
attribute2 VARCHAR(20)
);
table 이름 옆에 괄호parenthesis 안에는 table을 구성한 각 column의 정보가 들어감.
column 이름, 자료형 순.
모든 요소가 unique해서 PRIMARY KEY로 쓸 attribute는 뒤에 PRIMARY KEY가 추가로 붙음.
이름에 언더바 사용 가능
혹은 위의 표는 아래 SQL문과도 의미가 같음
CREATE TABLE tablename (
row_id INT,
attribute1 DECIMAL(3,10),
attribute2 VARCHAR(20),
PRYMARY KEY(table_id)
);
Describe
DESCRIBE tablename;
하면 table의 Schema를 출력해줌.
Drop (table 삭제)
DROP TABLE tablename;
Alter (schema 수정(column 추가, 제거))
ALTER TABLE tablename ADD column_name DECIMAL(10,20);
column_name이란 column을 tablename이란 table에 추가하는 것
ALTER TABLE tablename DROP column_name;
column_name이란 column 제거.
Inserting Data
위에서 만든 저 정체불명의 tablename이라는 table을 계속 쓰겠음.
tablename은 INT인 row_id, DECIMAL(3,10)인 attribute1, VARCHAR(20)인 attribute2가 있음
여기에 데이터를 집어넣으려면
INSERT INTO tablename VALUES(1, 123.4567, ‘some kind of string’);
잘 집어넣어졌는지 보려면
SELECT * FROM tablename;
만약 모든 attribute를 채우지 않고, 부분적으로만 채우고 싶다면
INSERT INTO tablename(row_id, attribute2) VALUES(2, ‘blah blah’);
하면 채워지지 않은 attribute1은 NULL이 되던가 default value가 되겠지
이미 있는 primary key를 insert하려고 하면 애러가 뜬다. 매번 unique 한 걸로 해줘야 함.
Constraints
not null, Unique
CREATE TABLE tablename (
row_id INT,
attribute1 DECIMAL(3,10) NOT NULL, --not null
attribute2 VARCHAR(20) UNIQUE, --unique
PRYMARY KEY(table_id)
);
primary key는 그 자체로 not null에 unique임
Default value
CREATE TABLE tablename (
row_id INT,
attribute1 DECIMAL(3,10) DEFAULT 12.34,--값을 안넣으면 디폴트로 12.34가 들어감.
attribute2 VARCHAR(20),
PRYMARY KEY(table_id)
);
AUTO_INCREMENT
CREATE TABLE tablename (
row_id INT AUTO_INCREMENT,
attribute1 DECIMAL(3,10),
attribute2 VARCHAR(20),
PRYMARY KEY(table_id)
);
이러면 id 지정 안해줘도 알아서 올라감.
근데 데이터 입력할 때 어떤 값들을 넣을지 지정해줘야함.(id를 빼야 하니까)
Update & Delete
UPDATE
UPDATE tablename SET attribute1=1.1 WHERE attribute1=1.11;
UPDATE tablename SET attribute1=3.74675 WHERE attribute2='somewhere';
UPDATE tablename SET attribute1=123.123 WHERE attribute1=1.11 OR attribute=1.22;
UPDATE tablename SET attribute1=1.1, attribute2="so on" WHERE row_id=3;
UPDATE tablename SET attribute1=0.0; --전부 다 바꾸는 거.
DELETE
DELETE FROM tablename WHERE row_id=3;
WHERE뒤에 조건 붙이는 방식은 다 같음.
Basic Queries
query란
SQL에서 데이터베이스에 정보를 요청하기 위한 구문
SELECT
SELECT * FROM tablename; -- *은 row에 있는 거 다 가져오겠단 소리
SELECT attribute1 FROM tablename;
SELECT attribute1, attribute2 FROM tablename;
SELECT tablename.attribute1 FROM tablename;
--걍 더 clear(명확)하게 이렇게 쓸 수도 있음.
--어떤 table의 attribute인지 명확하게 보이니까.
ORDER (정렬)
SELECT attribute1, attribute2
FROM tablename
ORDER BY attribute1;--정렬. default는 오름차순(ascending order)
--그리고 이렇게 항목별로 줄바꿈하는게 훨 보기 좋음. 이렇게 쓰길 권장하심.
SELECT attribute1, attribute2
FROM tablename
ORDER BY attribute1 DESC;--정렬. 이거는 내림차순(descending order)
--오름차순을 명시적으로 하려면 ASC로 적으면 됨.
SELECT attribute1, attribute2
FROM tablename
ORDER BY attribute1 DESC;--정렬. 이거는 내림차순(descending order)
--오름차순을 명시적으로 하려면 ASC로 적으면 됨.
SELECT *
FROM tablename
ORDER BY attribute1, row_id;--두개값 가지고 정렬도 되고.
LIMIT (개수 제한)
LIMIT 2; --조건에 맞는 row 최대 2개까지만 주세요.
당연한 얘기지만 order, where랑도 섞을수 있고.
WHERE에 올 수 있는 비교 연산자
-- <, >, <=, >=, =, <>(not equal to), AND, OR
IN
SELECT *
FROM tablename
WHERE attribute2 IN ('wilson', 'william', 'willy');
--attribute2가 paranthasis 안에 있는 value중 하나면 참
위에는 없는 명령어들
USE
USE databaseName;
SHOW
SHOW DATABASES;
SHOW TABLES;
SHOW TABLES FROM databaseName;
SHOW COLUMNS FROM tableName;
SHOW TABLE STATUS;
SHOW TABLE STATUS FROM databaseName;
SHOW STATUS; #서버 상태 보기
주석
#하고 적으면 됨. 이건 mySQL이 이런거. --쓰는것도 있을텐데
Timestamp difference
https://learnsql.com/cookbook/how-to-calculate-the-difference-between-two-timestamps-in-mysql/
timestampdiff
To calculate the difference between the timestamps in MySQL, use the [TIMESTAMPDIFF(unit, start, end)](<https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_timestampdiff>) function. The unit argument can be MICROSECOND , SECOND , MINUTE , HOUR , DAY , WEEK , MONTH , QUARTER , or YEAR . To get the difference in seconds as we have done here, choose SECOND . To get the difference in minutes, choose MINUTE ; for the difference in hours, choose HOUR , etc. The end and the start arguments are the ending timestamp and the starting timestamp, respectively (here, departure and arrival , respectively ).
CHARACTER SET 바꾸기(유니코드를 쓰기 위함)
https://dev.mysql.com/doc/refman/8.0/en/charset-column.html
CREATE TABLE english_names
(id INT,
name VARCHAR(40) CHARACTER SET utf8mb4
);
첨에 mariaDB 참고했다가, 안됨. 이 문법은 다 다른가보네.
https://cirius.tistory.com/1769
utf8mb4랑 utf8의 차이는, utf8은 이모지가 입력이 안된다. utf8mb4는 이모지 입력이 된다.
NOT NULL보다 선행되야 한다. 이게 순서가 있네. 몰랐네.
row 개수 세기
SELECT COUNT(*) FROM table_name;
문자열 형태의 ip 주소를 int로 변환
SELECT INET_ATON('127.0.0.1');
SELECT INET_NTOA(3520061480); #역함수임
sql문 안에 쓸 땐 SELSCT 없이 INET_ATON(<address>)만 쓰면 됨. 저거 자체가 함수임.
문자열 검색
'공부 > etc' 카테고리의 다른 글
git, github 정리 (0) | 2022.09.24 |
---|