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 MICROSECONDSECONDMINUTEHOURDAYWEEKMONTHQUARTER , 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 arrivalrespectively ).

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>)만 쓰면 됨. 저거 자체가 함수임.

문자열 검색

https://lollolzkk.tistory.com/44

'공부 > etc' 카테고리의 다른 글

git, github 정리  (0) 2022.09.24

내 실력이 오름에 따라 점차점차 업데이트 될 문서

 

Git and GitHub for Beginners - Crash Course

https://www.youtube.com/watch?v=RGOj5yH7evk

Terms (단어)

directory 폴더, 경로

repository(줄여서 repo) 프로젝트?

SSH key는 안 다룰거임. 이해 못함.

making a repository

우측 상단에 저거 누르면 empty repository를 만들 수 있음.

그다음 command로는

먼저 로컬 프로젝트 폴더에서

git init

하면 .git폴더가 만들어짐

그리고나서 그 새로만든 repo의 SSH 뭐시기를 복사해온 다음

git remote add origin git@github.com:01~~~(복사한 거)

하면 앞으로 push하면 새로 만든 repo에 들어감.

git remote -v

하면 잘 됐는지 확인할 수 있음.

SSH Keys

이거 안하니까 푸쉬가 안되더라.

https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

You can access and write data in repositories on GitHub.com using SSH (Secure Shell Protocol).

cmd창에

ssh-keygen -t rsa -b 4096 -C “<email address>”

하고 이후 물어보는거 잘 적으면 됨.

처음 물어보는건 키 파일 이름

두번째 물어보는건 암호인가.

-C는 uppercase임에 유의

이러고 나면 위 명령어를 실행시킨 경로에

keyname

keyname.pub

두개의 파일이 만들어짐. .pub은 공개키임. 다른 사람이 봐도 됨

.pub이 아닌 거는 private key임. 혼자 안전하게 간직하세요.

.pub파일의 내용을 복사하고서

github page에 우측 상단에서

Settings > SSH and GPG keys > SSH keys 옆에있는 New SSH key버튼

title은 그냥 본인이 알아볼 수있게 지으면 되고

그 아래 key에 복사한 내용을 붙여넣기

로컬키는 어케 하냐면

ssh-add -K  ~/.ssh/{키 이름}

하라는데

user폴더에 위에서 만든 private key를 넣고(.ssh폴더가 user에 있길래.)

우분투 쉘 틀어서 경로를 잘 이동해서

ssh-add -K  ./.ssh/{키 이름}

했더니

Enter PIN for authenticator:

이렇게 뜨고 키 생성할 때 passphrase 입력한거 쳤더니 애러 뜸.(사실 내가 어떤 passphrase했는지 기억이 안남.)

그래서 알아보니 -K를 빼는 법이 있다고 함.

ssh-add  ~/.ssh/{키 이름}

그랬더니 아래와 같은 오류가 뜸

Permissions 0777 for './.ssh/{키 이름}' are too open. It is required that your private key files are NOT accessible by others. This private key will be ignored.

구글링했더니

chmod 400 ./{key_name}

하라는 말이 있어서 했는데, 0777이 0555로 바뀜…

또또 알아보니

https://stackoverflow.com/questions/39404087/pem-file-permissions-on-bash-on-ubuntu-on-windows

key가 우분투상에 home/{username} 에 있어야 chmod 명령어가 잘 작동한다고 함.

mv 명령어로 옮기고 ssh-add명령어 실행했더니 passphrase 묻고 잘 실행됨.

근데 여전히 푸쉬가 안됨

다시 ssh-add 했더니

Could not open a connection to your authentication agent.

이럼.

아… key 이름은 id_rsa여야 하고 user폴더에 있는 .ssh폴더 안에 있어야함.

아니 나는 이름 맘대로 해도 되는 줄 알았지.

ssh -vT [git@github.com](<mailto:git@github.com>)

이 명령어 쳐서 알았다.

commands

git clone

로컬로 깃헙 레포 가져오는 거.

add

git add <filename>

변경사항 담는거.

filename 대신 온점(.) 적으면 modified, 새로 생긴 거 다 담김

git commit -m “commit name”

reset

git add . 한거 되돌리고 싶을 때

git reset //하면 전체 되돌리기
git reset <filename> //하면 특정 파일만 되돌리기

push

git push -u origin master

깃 레포에 업데이트 하는 거.

-u 뒤로는 한번 쓰고나면 이후 push할 때는 안 적어도 됨.

-u 안적고 하면 계속 적어야함.

origin은 repo 위치를 나타냄.

master은 branch임. 다른 branch에서 작업할 땐 저게 바뀌겠지.

pull

git pull

변경사항 로컬로 가져오는 거

status

git status

어떤게 add돼있고 안 돼있는지 check

diff

git diff

뭐가 달라졌는지 +, -를 다 보여줌.

branching

git branch

지금 repo의 branch정보랑 지금 어디 branch에 있는지 보여줌.

git checkout

branch 만들거나 이동할 수 있는 거.

other things

git 관련 정보는 프젝 폴더에 .git이라는 숨겨져있는 폴더 안에 저장된다.

윈도우 cmd도 되는지 모르겠는데(강의영상은 우분투에서 쓰는 명령어를 써서) branch이름 쓰다가 tab 치면 자동완성 해줌. 끄트머리 단어 입력하다 tab 해도 자동완성

.md 확장자는 마크다운이었다.

'공부 > etc' 카테고리의 다른 글

SQL Tutorial - Full Database Course for Beginners (1)  (0) 2022.09.26

+ Recent posts