사자자리
[MySQL] 본문
MySQL(MariaDB)의 구조
표(Table) | 데이터를 기록하는 최종적인 곳. 스프레드시트와 비슷한 구조. |
행(Row, Record) | 표의 한 행. 위의 표들은 2개의 행을 가지고 있다. |
열(Column) | 표의 한 열. 위의 표들은 4개의 열을 가지고 있다. |
데이터베이스(Database) | 서로 연관된 표들을 그룹핑해서 연관되지 않은 표들과 분리하는 것 수업에서는 데이터베이스라는 표현 대신 스키마(Schema)를 대신 사용한다. |
데이터베이스 서버(Database Server) | 많아진 데이터베이스(스키마)들이 저장되는 곳. |
MySQL(MariaDB)을 설치한 것 = 데이터베이스 서버라는 프로그램을 설치한 것
데이터베이스의 효용
보안
- 파일은 운영체제만 뚫리면 무주공당(임자가 없는 빈집)이다.
- 하지만, 데이터베이스는 자체적인 보안 체계를 가지고 있기 때문에 데이터를 더 안전하게 보관할 수 있다.
- 또한, 권한 기능이 있어서 데이터베이스 서버에 여러 사람이 등록해도 그들에게 권한을 차등적으로 줄 수 있다.
데이터베이스의 4가지 작업
Create Read Update Delete
데이터베이스(스키마)
데이터베이스(스키마) 생성하기: CREATE DATABASE [DB명];
MariaDB [(none)]> CREATE DATABASE opentutorials; --opentutorials라는 이름의 DB 생성
Query OK, 1 row affected (0.001 sec)
MariaDB [(none)]> CREATE DATABASE opentutorials; --이미 있는 DB를 생성하려고 할 경우
ERROR 1007 (HY000): Can't create database 'opentutorials'; database exists
데이터베이스(스키마) 삭제하기: DROP DATABASE [DB명];
MariaDB [(none)]> CREATE DATABASE Regulus; --Regulus라는 DB 생성
Query OK, 1 row affected (0.001 sec)
MariaDB [(none)]> DROP DATABASE Regulus; --Regulus 삭제
Query OK, 0 rows affected (0.044 sec)
데이터베이스(스키마) 리스트 보기: SHOW DATABASES;
MariaDB [(none)]> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| opentutorials |
| performance_schema |
| test |
+--------------------+
5 rows in set (0.030 sec)
데이터베이스(스키마) 사용하기: USE [DB명];
MariaDB [(none)]> USE opentutorials;
Database changed
MariaDB [opentutorials]> --지금부터 내리는 명령을 이 데이터베이스(스키마)에 있는 표를 대상으로 실행한다.
표(Table)
표 생성하기: CREATE TABLE [table명]( );
- 세미콜론(;)을 끝에 붙이지 않고 Enter 키를 누르면 실행되지 않고 다음 줄로 넘어간다.
MariaDB [(none)]> USE opentutorials;
Database changed
MariaDB [opentutorials]> CREATE TABLE topic (
-> id INT(11) NOT NULL AUTO_INCREMENT, #AUTO_INCREMENT: 자동으로 1씩 증가한다.
-> title VARCHAR(100) NOT NULL, #NOT NULL: NULL 값을 저장할 수 없다.
-> description TEXT NULL, #TEXT: column의 데이터타입을 강제할 수 있다.
-> created DATETIME NOT NULL,
-> author VARCHAR(30) NULL,
-> profile VARCHAR(100) NULL,
-> PRIMARY KEY(id) #PRIMARY KEY: NULL 값과 중복된 값을 가지면 안 된다.
-> );
Query OK, 0 rows affected (0.098 sec)
표 리스트 보기: SHOW TABLES;
MariaDB [opentutorials]> SHOW TABLES;
+-------------------------+
| Tables_in_opentutorials |
+-------------------------+
| topic |
+-------------------------+
1 row in set (0.001 sec)
표의 정보 보기: DESC [table명];
MariaDB [opentutorials]> DESC topic;
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| title | varchar(100) | NO | | NULL | |
| description | text | YES | | NULL | |
| created | datetime | NO | | NULL | |
| author | varchar(30) | YES | | NULL | |
| profile | varchar(100) | YES | | NULL | |
+-------------+--------------+------+-----+---------+----------------+
6 rows in set (0.047 sec)
표에 데이터 입력하기: INSERT INTO [table명](column명, ...) VALUES(입력할 데이터, ...);
MariaDB [opentutorials]> INSERT INTO topic(title, description, created, author, profile) VALUES('MySQL', 'MySQL is ...', NOW(), 'Regulus', 'wizard');
Query OK, 1 row affected (0.088 sec)
MariaDB [opentutorials]> INSERT INTO topic(title, description, created, author, profile) VALUES('ORACLE', 'ORACLE is ...', NOW(), 'Sirius', 'wizard');
Query OK, 1 row affected (0.008 sec)
MariaDB [opentutorials]> INSERT INTO topic(title, description, created, author, profile) VALUES('SQL Server', 'SQL Server is ...', NOW(), 'James', 'wizard');
Query OK, 1 row affected (0.005 sec)
MariaDB [opentutorials]> INSERT INTO topic(title, description, created, author, profile) VALUES('PostgreSQL', 'PostgreSQL is ...', NOW(), 'Remus', 'wizard');
Query OK, 1 row affected (0.006 sec)
MariaDB [opentutorials]> INSERT INTO topic(title, description, created, author, profile) VALUES('MongoDB', 'MongoDB is ...', NOW(), 'Harry', 'wizard');
Query OK, 1 row affected (0.005 sec)
https://www.techonthenet.com/mariadb/datatypes.php
MariaDB: Data Types
MariaDB: Data Types The following is a list of datatypes available in MariaDB, which includes string, numeric, date/time, and large object datatypes. String Datatypes The following are the String Datatypes in MariaDB: Data Type Syntax Maximum Size Explanat
www.techonthenet.com
SELECT
SELECT 문법: https://mariadb.com/kb/en/select/
SELECT
SQL statement used primarily for retrieving data from a MariaDB database.
mariadb.com
SELECT [표현];
MariaDB [opentutorials]> SELECT 1+1;
+-----+
| 1+1 |
+-----+
| 2 |
+-----+
1 row in set (0.003 sec)
MariaDB [opentutorials]> SELECT "Regulus Black";
+---------------+
| Regulus Black |
+---------------+
| Regulus Black |
+---------------+
1 row in set (0.000 sec)
SELECT [column명] FROM [table명];
MariaDB [opentutorials]> SELECT * FROM topic; #모든(*) column
+----+------------+-------------------+---------------------+---------+---------+
| id | title | description | created | author | profile |
+----+------------+-------------------+---------------------+---------+---------+
| 1 | MySQL | MySQL is ... | 2022-07-28 18:26:56 | Regulus | wizard |
| 2 | ORACLE | ORACLE is ... | 2022-07-28 18:28:54 | Sirius | wizard |
| 3 | SQL Server | SQL Server is ... | 2022-07-28 18:30:01 | James | wizard |
| 4 | PostgreSQL | PostgreSQL is ... | 2022-07-28 18:30:43 | Remus | wizard |
| 5 | MongoDB | MongoDB is ... | 2022-07-28 18:31:47 | Harry | wizard |
+----+------------+-------------------+---------------------+---------+---------+
5 rows in set (0.001 sec)
MariaDB [opentutorials]> SELECT id, title, author FROM topic;
+----+------------+---------+
| id | title | author |
+----+------------+---------+
| 1 | MySQL | Regulus |
| 2 | ORACLE | Sirius |
| 3 | SQL Server | James |
| 4 | PostgreSQL | Remus |
| 5 | MongoDB | Harry |
+----+------------+---------+
5 rows in set (0.001 sec)
SELECT [column명] FROM [table명] WHERE [조건]; | 조건에 해당하는 행만 출력한다. |
SELECT [column명] FROM [table명] ORDER BY [column명] ASC/DESC; | column의 오름차순/내림차순으로 출력한다. |
SELECT [column명] FROM [table명] LIMIT [숫자]; | 출력되는 행의 개수를 제한한다. |
MariaDB [opentutorials]> SELECT * FROM topic WHERE author = 'Regulus';
+----+-------+--------------+---------------------+---------+---------+
| id | title | description | created | author | profile |
+----+-------+--------------+---------------------+---------+---------+
| 1 | MySQL | MySQL is ... | 2022-07-28 18:26:56 | Regulus | wizard |
+----+-------+--------------+---------------------+---------+---------+
1 row in set (0.000 sec)
MariaDB [opentutorials]> SELECT * FROM topic ORDER BY id DESC LIMIT 3;
+----+------------+-------------------+---------------------+--------+---------+
| id | title | description | created | author | profile |
+----+------------+-------------------+---------------------+--------+---------+
| 5 | MongoDB | MongoDB is ... | 2022-07-28 18:31:47 | Harry | wizard |
| 4 | PostgreSQL | PostgreSQL is ... | 2022-07-28 18:30:43 | Remus | wizard |
| 3 | SQL Server | SQL Server is ... | 2022-07-28 18:30:01 | James | wizard |
+----+------------+-------------------+---------------------+--------+---------+
3 rows in set (0.001 sec)
UPDATE
UPDATE 문법: https://mariadb.com/kb/en/update/
UPDATE
Modify rows in one or more tables.
mariadb.com
UPDATE [table명] SET [변경할 내용] WHERE [조건];
- WHERE [조건]이 없으면, table의 모든 행이 변경된다.
MariaDB [opentutorials]> UPDATE topic SET profile = 'werewolf' WHERE author = 'Remus';
Query OK, 1 row affected (0.015 sec)
Rows matched: 1 Changed: 1 Warnings: 0
MariaDB [opentutorials]> SELECT * FROM topic;
+----+------------+-------------------+---------------------+---------+----------+
| id | title | description | created | author | profile |
+----+------------+-------------------+---------------------+---------+----------+
| 1 | MySQL | MySQL is ... | 2022-07-28 18:26:56 | Regulus | wizard |
| 2 | ORACLE | ORACLE is ... | 2022-07-28 18:28:54 | Sirius | wizard |
| 3 | SQL Server | SQL Server is ... | 2022-07-28 18:30:01 | James | wizard |
| 4 | PostgreSQL | PostgreSQL is ... | 2022-07-28 18:30:43 | Remus | werewolf |
| 5 | MongoDB | MongoDB is ... | 2022-07-28 18:31:47 | Harry | wizard |
+----+------------+-------------------+---------------------+---------+----------+
5 rows in set (0.001 sec)
DELETE
DELETE 문법: https://mariadb.com/kb/en/delete/
DELETE
Delete rows from one or more tables.
mariadb.com
DELETE FROM [table명] WHERE [조건];
- WHERE [조건]이 없으면, table의 모든 행이 삭제된다.
MariaDB [opentutorials]> DELETE FROM topic WHERE author = 'Harry';
Query OK, 1 row affected (0.004 sec)
MariaDB [opentutorials]> SELECT * FROM topic;
+----+------------+-------------------+---------------------+---------+----------+
| id | title | description | created | author | profile |
+----+------------+-------------------+---------------------+---------+----------+
| 1 | MySQL | MySQL is ... | 2022-07-28 18:26:56 | Regulus | wizard |
| 2 | ORACLE | ORACLE is ... | 2022-07-28 18:28:54 | Sirius | wizard |
| 3 | SQL Server | SQL Server is ... | 2022-07-28 18:30:01 | James | wizard |
| 4 | PostgreSQL | PostgreSQL is ... | 2022-07-28 18:30:43 | Remus | werewolf |
+----+------------+-------------------+---------------------+---------+----------+
4 rows in set (0.000 sec)
표 이름 바꾸기: RENAME TABLE [기존 table명] TO [새 table명];
MariaDB [opentutorials]> SHOW TABLES;
+-------------------------+
| Tables_in_opentutorials |
+-------------------------+
| topic |
+-------------------------+
1 row in set (0.003 sec)
MariaDB [opentutorials]> RENAME TABLE topic TO topic_backup;
Query OK, 0 rows affected (0.023 sec)
MariaDB [opentutorials]> SHOW TABLES;
+-------------------------+
| Tables_in_opentutorials |
+-------------------------+
| topic_backup |
+-------------------------+
1 row in set (0.001 sec)
표 분리하기: 중복된 데이터가 있다는 것은 개선할 것이 있다는 것을 뜻한다.
MariaDB [opentutorials]> CREATE TABLE topic(
-> id INT(11) NOT NULL AUTO_INCREMENT,
-> title VARCHAR(30) NOT NULL,
-> description TEXT NULL,
-> created DATETIME NOT NULL,
-> author_id INT(11) NULL,
-> PRIMARY KEY(id)
-> );
Query OK, 0 rows affected (0.039 sec)
MariaDB [opentutorials]> DESC topic;
+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| title | varchar(30) | NO | | NULL | |
| description | text | YES | | NULL | |
| created | datetime | NO | | NULL | |
| author_id | int(11) | YES | | NULL | |
+-------------+-------------+------+-----+---------+----------------+
5 rows in set (0.017 sec)
MariaDB [opentutorials]> INSERT INTO topic VALUES(1, 'MySQL', 'MySQL is...', NOW(), 1);
Query OK, 1 row affected (0.004 sec)
MariaDB [opentutorials]> INSERT INTO topic VALUES(2, 'Oracle', 'Oracle is ...', NOW(), 1);
Query OK, 1 row affected (0.004 sec)
MariaDB [opentutorials]> INSERT INTO topic VALUES(3, 'SQL Server', 'SQL Server is ...', NOW(), 2);
Query OK, 1 row affected (0.005 sec)
MariaDB [opentutorials]> INSERT INTO topic VALUES(4, 'PostgreSQL', 'PostgreSQL is ...', NOW(), 3);
Query OK, 1 row affected (0.004 sec)
MariaDB [opentutorials]> INSERT INTO topic VALUES(5, 'MongoDB', 'MongoDB is ...', NOW(), 1);
Query OK, 1 row affected (0.003 sec)
MariaDB [opentutorials]> CREATE TABLE author (
-> id INT(11) NOT NULL AUTO_INCREMENT,
-> name VARCHAR(20) NOT NULL,
-> profile VARCHAR(200) NULL,
-> PRIMARY KEY(id)
-> );
Query OK, 0 rows affected (0.027 sec)
MariaDB [opentutorials]> DESC author;
+---------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| profile | varchar(200) | YES | | NULL | |
+---------+--------------+------+-----+---------+----------------+
3 rows in set (0.018 sec)
MariaDB [opentutorials]> INSERT INTO author VALUES(1,'egoing','developer');
Query OK, 1 row affected (0.005 sec)
MariaDB [opentutorials]> INSERT INTO author VALUES(2,'duru','database administrator');
Query OK, 1 row affected (0.004 sec)
MariaDB [opentutorials]> INSERT INTO author VALUES(3,'taeho','data scientist, developer');
Query OK, 1 row affected (0.003 sec)
MariaDB [opentutorials]> SELECT * FROM topic;
+----+------------+-------------------+---------------------+-----------+
| id | title | description | created | author_id |
+----+------------+-------------------+---------------------+-----------+
| 1 | MySQL | MySQL is ... | 2022-07-29 22:00:04 | 1 |
| 2 | Oracle | Oracle is ... | 2022-07-29 22:06:13 | 1 |
| 3 | SQL Server | SQL Server is ... | 2022-07-29 22:06:18 | 2 |
| 4 | PostgreSQL | PostgreSQL is ... | 2022-07-29 22:06:23 | 3 |
| 5 | MongoDB | MongoDB is ... | 2022-07-29 22:06:28 | 1 |
+----+------------+-------------------+---------------------+-----------+
5 rows in set (0.001 sec)
MariaDB [opentutorials]> SELECT * FROM author;
+----+--------+---------------------------+
| id | name | profile |
+----+--------+---------------------------+
| 1 | egoing | developer |
| 2 | duru | database administrator |
| 3 | taeho | data scientist, developer |
+----+--------+---------------------------+
3 rows in set (0.000 sec)
JOIN
MariaDB [opentutorials]> SELECT * FROM topic LEFT JOIN author ON topic.author_id = author.id;
+----+------------+-------------------+---------------------+-----------+------+--------+---------------------------+
| id | title | description | created | author_id | id | name | profile |
+----+------------+-------------------+---------------------+-----------+------+--------+---------------------------+
| 1 | MySQL | MySQL is ... | 2022-07-29 22:00:04 | 1 | 1 | egoing | developer |
| 2 | Oracle | Oracle is ... | 2022-07-29 22:06:13 | 1 | 1 | egoing | developer |
| 3 | SQL Server | SQL Server is ... | 2022-07-29 22:06:18 | 2 | 2 | duru | database administrator |
| 4 | PostgreSQL | PostgreSQL is ... | 2022-07-29 22:06:23 | 3 | 3 | taeho | data scientist, developer |
| 5 | MongoDB | MongoDB is ... | 2022-07-29 22:06:28 | 1 | 1 | egoing | developer |
+----+------------+-------------------+---------------------+-----------+------+--------+---------------------------+
5 rows in set (0.007 sec)
MariaDB [opentutorials]> SELECT topic.id, title, description, created, name, profile FROM topic LEFT JOIN author ON topic.author_id = author.id;
+----+------------+-------------------+---------------------+--------+---------------------------+
| id | title | description | created | name | profile |
+----+------------+-------------------+---------------------+--------+---------------------------+
| 1 | MySQL | MySQL is ... | 2022-07-29 22:00:04 | egoing | developer |
| 2 | Oracle | Oracle is ... | 2022-07-29 22:06:13 | egoing | developer |
| 3 | SQL Server | SQL Server is ... | 2022-07-29 22:06:18 | duru | database administrator |
| 4 | PostgreSQL | PostgreSQL is ... | 2022-07-29 22:06:23 | taeho | data scientist, developer |
| 5 | MongoDB | MongoDB is ... | 2022-07-29 22:06:28 | egoing | developer |
+----+------------+-------------------+---------------------+--------+---------------------------+
5 rows in set (0.002 sec)
- 데이터베이스 서버를 직접 다룰 수 없다. 데이터베이스 서버는 데이터베이스 클라이언트를 사용해야 한다.
- MySQL(MariaDB): MySQL Monitor. 데이터베이스 클라이언트 중 하나이다. MySQL Monitor와 MySQL Server는 같이 다운로드되기 때문에 어디에서나 사용할 수 있는 장점이 있지만, 명령어 기반 프로그램이기 때문에 명령어를 기억해야 한다는 단점이 있다.
- MySQL Workbench: GUI 환경에서 데이터베이스를 다룰 수 있는 프로그램이다. 마우스로 조작할 수 있다
1. MySQL Workbench 다운로드: https://dev.mysql.com/downloads/workbench/
MySQL :: Download MySQL Workbench
Select Operating System: Select Operating System… Microsoft Windows Ubuntu Linux Red Hat Enterprise Linux / Oracle Linux Fedora macOS Source Code Select OS Version: All Windows (x86, 64-bit) Recommended Download: Other Downloads: Windows (x86, 64-bit), M
dev.mysql.com
-h: host의 약자. 인터넷에 연결되어 있는 각각의 컴퓨터. 인터넷을 통해 다른 컴퓨터에 있는 mysql 서버에 접속하려고 하면 그 서버에 해당되는 컴퓨터의 주소를 적는다. 구글 직원이면 -hgoogle.com. 그러나 우리는 지금 mysql client와 mysql server가 같은 컴퓨터에 위치하고 있다. mysql client가 설치되어있는 컴퓨터 자신을 가리키는 특수한 도메인은 localhost이다. localhost와 같은 의미의 ip주소는 127.0.0.1이다.
2. MySQL Connections: 플러스(+) 버튼
'웹기초 > 생활코딩 DATABASE2 - MySQL' 카테고리의 다른 글
[MySQL] MariaDB 다운로드와 접속 (0) | 2022.07.24 |
---|