关系型数据库介绍
1. 关系型数据库介绍1.1 数据结构模型数据结构模型主要有:层次模型网状结构关系模型关系模型:二维关系:row,column数据库管理系统:DBMS关系:Relational,RDBMS1.2 RDBMS专业名词常见的关系型数据库管理系统:MySQL:MySQL,MariaDB,Percona-ServerPostgreSQL:简称为pgsqlOracleMSSQL**SQL:**Structu
·
1. 关系型数据库介绍
1.1 数据结构模型
数据结构模型主要有:
- 层次模型
- 网状结构
- 关系模型
关系模型:
二维关系:row,column
数据库管理系统:DBMS
关系:Relational,RDBMS
1.2 RDBMS专业名词
常见的关系型数据库管理系统:
- MySQL:MySQL,MariaDB,Percona-Server
- PostgreSQL:简称为pgsql
- Oracle
- MSSQL
**SQL:**Structure Query Language,结构化查询语言
**约束:**constraint,向数据表提供的数据要遵守的限制
- 主键约束:一个或多个字段的组合,填入的数据必须能在本表中唯一标识本行。且必须提供数据,不能为空(NOT NULL)。
- 一个表只能存在一个
- 惟一键约束:一个或多个字段的组合,填入的数据必须能在本表中唯一标识本行。允许为空(NULL)
- 一个表可以存在多个
- 外键约束:一个表中的某字段可填入数据取决于另一个表的主键已有的数据
- 检查性约束
**索引:**将表中的一个或多个字段中的数据复制一份另存,并且这些数据需要按特定次序排序存储
1.3 关系型数据库的常见组件
关系型数据库的常见组件有:
- 数据库:database
- 表:table,由行(row)和列(column)组成
- 索引:index
- 视图:view
- 用户:user
- 权限:privilege
- 存储过程:procedure
- 存储函数:function
- 触发器:trigger
- 事件调度器:event scheduler
1.4 SQL语句
SQL语句有三种类型:
- DDL:Data Defination Language,数据定义语言
- DML:Data Manipulation Language,数据操纵语言
- DCL:Data Control Language,数据控制语言
SQL语句类型 | 对应操作 |
---|---|
DDL | CREATE:创建 DROP:删除 ALTER:修改 |
DML | INSERT:向表中插入数据 DELETE:删除表中数据 UPDATE:更新表中数据 SELECT:查询表中数据 |
DCL | GRANT:授权 REVOKE:移除授权 |
2. mysql安装与配置
2.1 mysql安装
mysql安装方式有三种:
- 源代码:编译安装
- 二进制格式的程序包:展开至特定路径,并经过简单配置后即可使用
- 程序包管理器管理的程序包:
- rpm:有两种
- OS Vendor:操作系统发行商提供的
- 项目官方提供的
- deb
- rpm:有两种
[root@localhost yum.repos.d]# yum -y install mariadb mariadb-server
Updating Subscription Management repositories.
Unable to read consumer identity
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
上次元数据过期检查:0:09:08 前,执行于 2021年08月23日 星期一 20时57分49秒。
依赖关系解决。
===============================================================================================================
软件包 架构 版本 仓库 大小
===============================================================================================================
安装:
mariadb x86_64 3:10.3.28-1.module_el8.3.0+757+d382997d AppStream 6.0 M
mariadb-server x86_64 3:10.3.28-1.module_el8.3.0+757+d382997d AppStream 16 M
安装依赖关系:
mariadb-common x86_64 3:10.3.28-1.module_el8.3.0+757+d382997d AppStream 64 k
mariadb-connector-c x86_64 3.1.11-2.el8_3 AppStream 200 k
mariadb-connector-c-config noarch 3.1.11-2.el8_3 AppStream 15 k
mariadb-errmsg x86_64 3:10.3.28-1.module_el8.3.0+757+d382997d AppStream 234 k
perl-Carp noarch 1.42-396.el8 base 30 k
perl-DBD-MySQL x86_64 4.046-3.module_el8.1.0+203+e45423dc AppStream 156 k
......
2.2 mariadb配置
#启动mysql并设置开机自动启动
systemctl enable --now mariadb
systemctl status mariadb
[root@localhost etc]# systemctl enable --now mariadb
Created symlink /etc/systemd/system/mysql.service → /usr/lib/systemd/system/mariadb.service.
Created symlink /etc/systemd/system/mysqld.service → /usr/lib/systemd/system/mariadb.service.
Created symlink /etc/systemd/system/multi-user.target.wants/mariadb.service → /usr/lib/systemd/system/mariadb.service.
[root@localhost etc]# systemctl status mariadb
● mariadb.service - MariaDB 10.3 database server
Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
Active: active (running) since Mon 2021-08-23 21:09:47 CST; 2min 7s ago
Docs: man:mysqld(8)
https://mariadb.com/kb/en/library/systemd/
Main PID: 62683 (mysqld)
Status: "Taking your SQL requests now..."
Tasks: 30 (limit: 23790)
Memory: 85.4M
CGroup: /system.slice/mariadb.service
└─62683 /usr/libexec/mysqld --basedir=/usr
#确保3306端口已经监听起来
ss -antl
[root@localhost etc]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 80 *:3306 *:*
LISTEN 0 128 [::]:22 [::]:*
#在日志文件中找出临时密码
grep "password" /var/log/mysqld.log
#使用获取到的临时密码登录mysql
[root@localhost etc]# mysql -uroot -p
Enter password: //此处输入密码 默认无密码
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 8
Server version: 10.3.28-MariaDB MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> exit //看到有这样的标识符则表示成功登录了
Bye
//修改mysql登录密码
MariaDB [(none)]> use mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MariaDB [mysql]> ALTER USER 'root'@'localhost' IDENTIFIED BY '123';
Query OK, 0 rows affected (0.000 sec)
//用新密码登陆测试
[root@localhost etc]# mysql -uroot -p123
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 11
Server version: 10.3.28-MariaDB MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>
3. mysql的程序组成
- 客户端
- mysql:CLI交互式客户端程序
- mysql_secure_installation:安全初始化,强烈建议安装完以后执行此命令
- mysqldump:mysql备份工具
- mysqladmin
- 服务器端
- mysqld
3.1 mysql工具使用
//语法:mysql [OPTIONS] [database]
//常用的OPTIONS:
-uUSERNAME //指定用户名,默认为root
-hHOST //指定服务器主机,默认为localhost,推荐使用ip地址
-pPASSWORD //指定用户的密码
-P# //指定数据库监听的端口,这里的#需用实际的端口号代替,如-P3307
-V //查看当前使用的mysql版本
-e //不登录mysql执行sql语句后退出,常用于脚本
[root@localhost etc]# mysql -V
mysql Ver 15.1 Distrib 10.3.28-MariaDB, for Linux (x86_64) using readline 5.1
[root@localhost etc]# mysql -uroot -p123 -h127.0.0.1
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 13
Server version: 10.3.28-MariaDB MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>
//注意,不推荐直接在命令行里直接用-pPASSWORD的方式登录,而是使用-p选项,然后交互式输入密码
[root@localhost etc]# mysql -uroot -p -h127.0.0.1
Enter password: //输入密码
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 15
Server version: 10.3.28-MariaDB MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>
不进入数据库查看表
[root@localhost etc]# mysql -uroot -p -h 127.0.0.1 -e 'SHOW DATABASES;'
Enter password: //输入密码
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
+--------------------+
3.2 服务器监听的两种socket地址
socket类型 | 说明 |
---|---|
ip socket | 默认监听在tcp的3306端口,支持远程通信 |
unix sock | 监听在sock文件上(/tmp/mysql.sock,/var/lib/mysql/mysql.sock) 仅支持本地通信 server地址只能是:localhost,127.0.0.1 |
4. mysql数据库操作
4.1 DDL操作
4.1.1 数据库操作
//创建数据库
//语法:CREATE DATABASE [IF NOT EXISTS] 'DB_NAME';
//创建数据库zxc
MariaDB [(none)]> create database zxc;
Query OK, 1 row affected (0.000 sec)
//查看当前实例有哪些数据库
MariaDB [(none)]> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| zxc |
+--------------------+
4 rows in set (0.000 sec)
//删除数据库
//语法:DROP DATABASE [IF EXISTS] 'DB_NAME';
//删除数据库zxc
MariaDB [(none)]> drop database zxc;
Query OK, 0 rows affected (0.000 sec)
MariaDB [(none)]> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
+--------------------+
3 rows in set (0.000 sec)
4.1.2 表操作
//创建表
//语法:CREATE TABLE table_name (col1 datatype 修饰符,col2 datatype 修饰符) ENGINE='存储引擎类型';
//在数据库zxc里创建表asd
MariaDB [(none)]> create database zxc; //创建数据库zxc
Query OK, 1 row affected (0.000 sec)
MariaDB [(none)]>
MariaDB [(none)]> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| zxc |
+--------------------+
4 rows in set (0.000 sec)
MariaDB [(none)]> use zxc; //使用数据库zxc
Database changed
MariaDB [zxc]> create table asd(id int(7) ,name varchar(5) not null ); //创建表asd
Query OK, 0 rows affected (0.003 sec)
MariaDB [zxc]>
MariaDB [zxc]> show tables; //查看有哪些表
+---------------+
| Tables_in_zxc |
+---------------+
| asd |
+---------------+
1 row in set (0.000 sec)
//查看当前数据库有哪些表
mysql> SHOW TABLES;
+----------------------+
| Tables_in_wangqingge |
+----------------------+
| wangqing |
+----------------------+
1 row in set (0.00 sec)
//删除表
//语法:DROP TABLE [ IF EXISTS ] 'table_name';
//删除表asd
MariaDB [zxc]> drop table asd;
Query OK, 0 rows affected (0.001 sec)
MariaDB [zxc]> show tables;
Empty set (0.000 sec)
4.1.3 用户操作
mysql用户帐号由两部分组成,如’USERNAME’@‘HOST’,表示此USERNAME只能从此HOST上远程登录
这里(‘USERNAME’@‘HOST’)的HOST用于限制此用户可通过哪些主机远程连接mysql程序,其值可为:
- IP地址,如:172.16.12.129
- 通配符
- %:匹配任意长度的任意字符,常用于设置允许从任何主机登录
- _:匹配任意单个字符
//数据库用户创建
//语法:CREATE USER 'username'@'host' [IDENTIFIED BY 'password'];
//创建数据库用户chenshunli
MariaDB [(none)]> create user 'chenshunli'@'%' identified by "123" ;
Query OK, 0 rows affected (0.000 sec)
//使用新创建的用户和密码登录
[root@localhost etc]# mysql -uchenshunli -p123
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 22
Server version: 10.3.28-MariaDB MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>
//删除数据库用户
//语法:DROP USER 'username'@'host';
[root@localhost etc]# mysql -uroot -p123 //退出用户后,切换root用户在进行删除操作
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 23
Server version: 10.3.28-MariaDB MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> drop user 'chenshunli'@'%' ;
Query OK, 0 rows affected (0.000 sec)
4.1.4 查看命令SHOW
MariaDB [(none)]> SHOW CHARACTER SET; //查看支持的所有字符集
+----------+-----------------------------+---------------------+--------+
| Charset | Description | Default collation | Maxlen |
+----------+-----------------------------+---------------------+--------+
| big5 | Big5 Traditional Chinese | big5_chinese_ci | 2 |
| dec8 | DEC West European | dec8_swedish_ci | 1 |
| cp850 | DOS West European | cp850_general_ci | 1 |
| hp8 | HP West European | hp8_english_ci | 1 |
| koi8r | KOI8-R Relcom Russian | koi8r_general_ci | 1 |
| latin1 | cp1252 West European | latin1_swedish_ci | 1 |
| latin2 | ISO 8859-2 Central European | latin2_general_ci | 1 |
| swe7 | 7bit Swedish | swe7_swedish_ci | 1 |
| ascii | US ASCII | ascii_general_ci | 1 |
| ujis | EUC-JP Japanese | ujis_japanese_ci | 3 |
| sjis | Shift-JIS Japanese | sjis_japanese_ci | 2 |
| hebrew | ISO 8859-8 Hebrew | hebrew_general_ci | 1 |
......
......
MariaDB [(none)]> SHOW ENGINES \G //查看当前数据库支持的所有存储引擎
*************************** 1. row ***************************
Engine: MEMORY
Support: YES
Comment: Hash based, stored in memory, useful for temporary tables
Transactions: NO
XA: NO
Savepoints: NO
*************************** 2. row ***************************
Engine: MRG_MyISAM
Support: YES
Comment: Collection of identical MyISAM tables
Transactions: NO
XA: NO
Savepoints: NO
*************************** 3. row ***************************
Engine: CSV
Support: YES
Comment: Stores tables as CSV files
Transactions: NO
XA: NO
Savepoints: NO
*************************** 4. row ***************************
MariaDB [(none)]> SHOW DATABASES; //查看数据库信息
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| zxc |
+--------------------+
4 rows in set (0.000 sec)
MariaDB [(none)]> SHOW TABLES FROM zxc; //不进入某数据库而列出其包含的所有表
+---------------+
| Tables_in_zxc |
+---------------+
| asd |
+---------------+
1 row in set (0.000 sec)
//查看表结构
//语法:DESC [db_name.]table_name;
MariaDB [(none)]> desc zxc.asd ;
+-------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------+------+-----+---------+-------+
| id | int(7) | YES | | NULL | |
| name | varchar(5) | NO | | NULL | |
+-------+------------+------+-----+---------+-------+
2 rows in set (0.001 sec)
//查看某表的创建命令
//语法:SHOW CREATE TABLE table_name;
MariaDB [(none)]> show create table zxc.asd;
+-------+----------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------+----------------------------------------------------------------------------------------------------------------------+
| asd | CREATE TABLE `asd` (
`id` int(7) DEFAULT NULL,
`name` varchar(5) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------+----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.000 sec)
//查看某表的状态
//语法:SHOW TABLE STATUS LIKE 'table_name'\G
MariaDB [(none)]> use zxc ; //进入数据库zxc
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MariaDB [zxc]>
MariaDB [zxc]> show table status like 'asd' \G
*************************** 1. row ***************************
Name: asd
Engine: InnoDB
Version: 10
Row_format: Dynamic
Rows: 0
Avg_row_length: 0
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 0
Auto_increment: NULL
Create_time: 2021-08-23 21:47:47
Update_time: NULL
Check_time: NULL
Collation: latin1_swedish_ci
Checksum: NULL
Create_options:
Comment:
Max_index_length: 0
Temporary: N
1 row in set (0.000 sec)
4.1.5 获取帮助
//获取命令使用帮助
//语法:HELP keyword;
mysql> HELP CREATE TABLE; //获取创建表的帮助
Name: 'CREATE TABLE'
Description:
Syntax:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
[table_options]
[partition_options]
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
[partition_options]
[IGNORE | REPLACE]
[AS] query_expression
......
......
4.1.5 获取帮助
//获取命令使用帮助
//语法:HELP keyword;
mysql> HELP CREATE TABLE; //获取创建表的帮助
Name: 'CREATE TABLE'
Description:
Syntax:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
[table_options]
[partition_options]
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
[partition_options]
[IGNORE | REPLACE]
[AS] query_expression
......
......
4.2 DML操作
DML操作包括增(INSERT)、删(DELETE)、改(UPDATE)、查(SELECT),均属针对表的操作。
4.2.1 INSERT语句
//DML操作之增操作insert
//语法:INSERT [INTO] table_name [(column_name,...)] {VALUES | VALUE} (value1,...),(...),...
MariaDB [(none)]> use zxc ;
Database changed
MariaDB [zxc]> insert into asd(id,name) value(1,'csl') ; //一次插入一条记录
Query OK, 1 row affected (0.001 sec)
MariaDB [zxc]> insert into asd(id,name) values(1,'csl') ,(2,'xk') ,(3,'cac') ; //一次插入多条记录
Query OK, 3 rows affected (0.001 sec)
Records: 3 Duplicates: 0 Warnings: 0
4.2.2 SELECT语句
字段column表示法
表示符 | 代表什么? |
---|---|
* | 所有字段 |
as | 字段别名,如col1 AS alias1 当表名很长时用别名代替 |
条件判断语句WHERE
操作类型 | 常用操作符 |
---|---|
操作符 | >,<,>=,<=,=,!= BETWEEN column# AND column# LIKE:模糊匹配 RLIKE:基于正则表达式进行模式匹配 IS NOT NULL:非空 IS NULL:空 |
条件逻辑操作 | AND OR NOT |
ORDER BY:排序,默认为升序(ASC)
ORDER BY语句 | 意义 |
---|---|
ORDER BY ‘column_name’ | 根据column_name进行升序排序 |
ORDER BY ‘column_name’ DESC | 根据column_name进行降序排序 |
ORDER BY ’column_name’ LIMIT 2 | 根据column_name进行升序排序 并只取前2个结果 |
ORDER BY ‘column_name’ LIMIT 1,2 | 根据column_name进行升序排序 并且略过第1个结果取后面的2个结果 |
//DML操作之查操作select
//语法:SELECT column1,column2,... FROM table_name [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];
MariaDB [(none)]> use zxc ;
Database changed
MariaDB [zxc]> select * from asd ;
+------+------+
| id | name |
+------+------+
| 1 | csl |
| 1 | csl |
| 2 | xk |
| 3 | cac |
+------+------+
4 rows in set (0.000 sec)
MariaDB [zxc]> select name from asd;
+------+
| name |
+------+
| csl |
| csl |
| xk |
| cac |
+------+
4 rows in set (0.000 sec)
MariaDB [zxc]> select name from asd where id=2 ;
+------+
| name |
+------+
| xk |
+------+
1 row in set (0.000 sec)
MariaDB [zxc]> select * from asd where name='xk' and id=2 ;
+------+------+
| id | name |
+------+------+
| 2 | xk |
+------+------+
1 row in set (0.000 sec)
MariaDB [zxc]> select * from asd order by name ;
+------+------+
| id | name |
+------+------+
| 3 | cac |
| 1 | csl |
| 1 | csl |
| 2 | xk |
+------+------+
4 rows in set (0.000 sec)
MariaDB [zxc]> select * from asd order by name desc ;
+------+------+
| id | name |
+------+------+
| 2 | xk |
| 1 | csl |
| 1 | csl |
| 3 | cac |
+------+------+
4 rows in set (0.000 sec)
MariaDB [zxc]> select * from asd order by name limit 2 ;
+------+------+
| id | name |
+------+------+
| 3 | cac |
| 1 | csl |
+------+------+
2 rows in set (0.000 sec)
MariaDB [zxc]> select * from asd order by id limit 1,2 ;
+------+------+
| id | name |
+------+------+
| 1 | csl |
| 2 | xk |
+------+------+
2 rows in set (0.000 sec)
更多推荐
已为社区贡献1条内容
所有评论(0)