mysql

mysql

数据库原理

数据的分类

在数据的获取和使用的过程中,根据数据的结构类型,将数据分成三类,分别是:结构化数据,半结构化数据,非结构化数据。

结构化数据

结构化数据一般是指可以用二维表来逻辑表达实现的数据。是有固定的格式和有限长度的数据,可以用关系型数据库表示和存储。

其特点是:数据以行为单位,一行数据表示一个实体信息,每一行数据的属性是相同的,存储在数据库中;能够用统一的数据类型和结构加以表示;也能够用二维表结构来逻辑表达实现,包含属性和元组。

半结构化数据

半结构化数据就是介于完全结构化数据和完全无结构的数据之间的数据。

半结构化数据是结构化数据的一种形式,它并不符合关系型数据库或其它数据表的形式关联起来的数据模型结构,但包含相关的标记,用来分隔语义元素及对记录和字段进行分层,数据的结构和内容混在一起,没有明显的区分,因此,这种数据也被称为自描述结构的数据。

非结构化数据

顾名思义,就是没有固定结构的数据,这种数据没有固定格式和有限长度,无法用数据库二维逻辑表来表现其结构,对于这类数据,一般进行整体存储。

典型的非结构化数据包括:二进制文件,音视频文件,位置信息等

数据库管理系统

相关概念

数据库:Database

数据库是按照一定的数据结构来组织,存储和管理数据的仓库。

是一个长期存储在计算机内的、有组织的、可共享的、统一管理的大量数据的集合。

数据库管理系统:Database Management System(DBMS)

数据库管理系统是一种操纵和管理数据库的大型软件,用于建立,使用和维护数据库,简称DBMS。

它对数据库进行统一的管理和控制,以保证数据库的安全性和完整性。

数据库管理员:Database Administrator(DBA)

DBA是从事管理和维护数据库管理系统(DBMS)的相关工作人员的统称,属于运维工程师的一个分支,主要负责业务数据库从设计、测试到部署交付的全生命周期管理。

DBA的核心目标是保证数据库管理系统的稳定性、安全性、完整性和高可用性能。

应用程序:Application

一个应用程序通常是指能够执行某种功能的软件程序。

数据库管理系统特点

  • 数据库管理系统中采用了复杂的数据模型表示数据结构,数据冗余小,易扩充,实现了数据共享。
  • 具有较高的数据和程序独立性。数据库的独立性表现在物理独立性和逻辑独立性两个方面。
  • 数据库管理系统为用户和应用程序提供了方便和统一的查询接口。
  • 数据库管理系统的存在,使得数据可以和应用程序解耦。
  • 数据库管理系统还具有并发控制,数据备份和恢复,完整性和安全性保障等功能。

数据库管理系统基本功能

  1. 数据的定义:DBMS提供了数据定义语言DDL,供用户定义数据库的三级模式结构,两级映像以及完整性约束和保密限制等约束。DDL主要用于建立、修改数据库的库结构。DDL所描述的库结构仅仅给出了数据库的框架,数据库的框架信息被存放在数据字典中。
  2. 数据操作:DBMS提供数据操作语言DML,供用户实现对数据的追加、删除、更新、查询等操作。
  3. 数据组织、存储与管理:DBMS要分类组织、存储和管理各种数据,包括数据字典、用户数据、存取路径等,需确定以何种文件结构和存取方式在存储级上组织这些数据,如何实现数据之间的联系。数据组织和存储的基本目标是提高存储空间利用率,选择合适的存取方法提高存取效率。
  4. 数据库的运行管理:数据库的运行管理功能是DBMS的运行控制、管理功能,包括多用户环境下的并发控制、安全性检查和存取限制控制、完整性检查和执行、运行日志的组织管理、事务的管理和自动恢复,即保证事务的原子性。这些功能保证了数据库系统的正常运行。
  5. 数据库的维护:这一部分包括数据库的数据载入、转换、转储、数据库的重组和重构以及性能监控等功能,这些功能分别由各个使用程序来完成。
  6. 数据库的保护:数据库中的数据是信息社会的战略资源,所以数据的保护至关重要。DBMS对数据库的保护通过4个方面来实现:数据库的恢复、数据库的并发控制、数据库的完整性控制、数据库安全性控制。DBMS的其他保护功能还有系统缓冲区的管理以及数据存储的某些自适应调节机制等。
  7. 通信:DBMS具有与操作系统的联机处理、分时系统及远程作业输入的相关接口,负责处理数据的传送。对网络环境下的数据库系统,还应该包括DBMS与网络中其他软件系统的通信功能以及数据库之间的互操作功能。

数据库管理系统的分类

层次数据库

层次模型数据库系统是最早研制成功的数据库系统,这种数据库中的数据被组织成一个树状模型,这种结构简单,但缺乏灵活性,各数据之间仅限于一对多的关系。

这种数据库最成功的典型代表是IBM的IMS(信息管理系统)。

网状数据库

网状数据库是采用网状原理和方法,以网状数据模型为基础建立的数据库。

网状数据模型是以记录类型为结点的网络结构,即一个结点可以有一个或多个下级结点,也可以有一个或多个上级结点,两个结点之间甚至可以有多种联系,两个记录类型之间的值可以是多对多的联系。

关系型数据库管理系统

是指包括相互联系的逻辑组织和存取这些数据的一套程序(数据库管理系统软件)。关系数据库管理系统就是管理关系数据库,并将数据逻辑组织的系统。

常见的关系型数据库管理系统有Oracle,MySQL,DB2,SQLServer等。

关系型数据库,是指采用了关系模型来组织数据的数据库,其以行和列的形式存储数据,以便于用户理解,关系型数据库这一系列的行和列被称为表,一组表组成了数据库。用户通过查询来检索数据库中的数据,而查询是一个用于限定数据库中某些区域的执行代码。

关系型数据库理论

E-R模型

ER模型,全称为实体联系模型、实体关系模型或实体联系模式图,它提供不受任何DBMS约束的面向用户的表达方法,在数据库设计中被广泛用作数据建模的工具。

E-R图模型的组成是由实体,属性和联系三部份组成。

实体:实体是数据的使用者,代表软件系统中客观存在的生活中的实物,同一类实体构成实体集。在ER图中,实体用矩形表示。

属性:实体中的所有特性称为属性,每个属性描述的是实体的单个特性。在ER图中,属性用椭圆形表示。

联系:描述了实体的属性之间的关联规则。在ER图中,联系用菱形表示。ER模型

联系类型

实体间的联系有三种类型:

一对一联系(1:1):例如,一个学号只能分配给一个同学,每个同学都有一个学号,则学号与同学的联系是一对一。

一对多联系(1:n):例如,一个老师可以教授多门课程,每门课程只能有一个老师教授,则老师与课程的联系是一对多。

多对多联系(m:n):例如,一个同学可以报名多门课程,每门课程下有多个同学,则同学与课程的联系是多对多。

数据的操作

数据库中对数据的操作主要包括增删改查

操作描述 作用 SQL关键字
Create 增加数据 Insert
Read 读取数据 Select
Update 更新数据 Update
Delete 删除数据 Delete

MySQL安装和基本使用

MySQL介绍

MySQL 的特性

  • MySQL是基于开源协议发布的,可以免费使用,也可以基于源码进行二次开发。
  • MySQL使用标准SQL语言进行管理。
  • MySQL可以运行于多个系统上,具有跨平台特性,并且支持多种语言。
  • MySQL使用插件式存储引擎,不同的存储引擎,有着不同的功能和特性,使用者可以根据需要灵活选择。
  • MySQL基于单进程,多线程的模式进行工作。
  • MySQL提供了大量的测试组件和诸多的扩展。

MySQL多实例

数据库多实例介绍

MySQL数据库来,就是在一台服务器上运行多个MySQL服务端进程,每个进程监听一个端口(3306,3307,3308),维护一套属于其自己的配置和数据,客户端使用不同的端口来连接具体服端进程,从而实现对不同的实例的操作。

多实例的优点

  • 节约硬件资源:在某些场景下,需要配置不同的MySQL数据库版本,而又没有足够多的服务器资源,则可以选择在一台服务器上用不同的版本实现多开来满足需求。
  • 便于对比:在一个完全相同的硬件环境中,运行不同的MySQL版本,使用相同的参数进行测试,调研时,可以最大程度的减少外部环境因素的影响,便于得出更准确的结论。
  • 便于管理:在一台服务器上运行多个实例,同理,只需要在这一台服务器上配置安全规则,就可以完成对多个实例的访问授权,而且对于数据库的备份,停启等工作,也只需要在这一台服务器上完成。

多实例的缺点

  • 资源抢占:一台服务器上运行多个服务实例,资源总量恒定,一个实例占用的资源无法被另一个实例所使用,在这种情况下,服务性能会受到影响,无法体现MySQL服务的实际性能。
  • 存在单点风险:一台服务器上部署多个服务实例,如果该服务器当机,则这多个服务实例都会受影响。

MySQL组成和常用工具

MySQL主要组成

服务端主要组成
程序 功能
mysqld_safe 安全启动脚本
mysqld 服务端程序,是mysql服务的核心程序
mysqld_multi 多实例工具
客户端主要组成
程序 功能
mysql 基于mysql协议的交互式CLI工具
mysqldump 备份工具
mysqladmin 服务端管理工具
mysqlimport 数据导入工具

MySQL客户端使用

MySQL服务基于C/S架构,用户主要使用客户端工具来与远程服务端进行连接,从而与MySQL服务进行交互。

bash 复制代码
#免密登录
[root@mysql ~]# mysql -uroot -pxiaomi
#将mysql root账号密码设置为空
mysql> alter user root@localhost identified by '';        
#退出mysql
mysql> quit                                               

#指定用户名,主机,端口
[root@mysql ~]# mysql -uroot -h127.0.0.1 -P3306 -pxiaomi
mysql>
执行完退出,非交互式执行
bash 复制代码
#环境准备
[root@mysql ~]# vim /root/test.sql
show databases;

#执行客户端命令
[root@mysql ~]# mysql -e "source /root/test.sql"
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

#管道执行
[root@mysql ~]# cat test.sql | mysql
Database
information_schema
mysql
performance_schema
sys
指定数据库
bash 复制代码
#默认
[root@mysql ~]# mysql
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

#指定数据库
[root@mysql ~]# mysql information_schema
mysql> select database();
+--------------------+
| database()         |
+--------------------+
| information_schema |
+--------------------+
1 row in set (0.00 sec)
显示当前数据库
mysql 复制代码
#显示当前数据库
mysql> \s
--------------
mysql  Ver 8.0.26 for Linux on x86_64 (Source distribution)
#连接ID
Connection id:          13
#当前使用的数据库
Current database:       information_schema
#连接使用的用户名
Current user:           root@localhost
#是否使用ssl
SSL:                    Not in use
Current pager:          stdout
Using outfile:          ''
Using delimiter:        ;
#版本
Server version:         8.0.26 Source distribution
#协议版本
Protocol version:       10
Connection:             Localhost via UNIX socket
#服务器编码
Server characterset:    utf8mb4
#数据库编码
Db     characterset:    utf8mb3
#客户端编码
Client characterset:    utf8mb4
Conn.  characterset:    utf8mb4
#连接使用的socket文件
UNIX socket:            /var/lib/mysql/mysql.sock
Binary data as:         Hexadecimal
#服务器运行时长
Uptime:                 6 min 31 sec
Threads: 2  Questions: 100  Slow queries: 0  Opens: 199  Flush tables: 3  Open tables: 118  Queries per second avg: 0.255
--------------
切换数据库
mysql 复制代码
mysql> 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
调用系统命令
bash 复制代码
#查看宿主机主机名,!号后面有空格
mysql> \! hostname;
mysql
自定义
bash 复制代码
#两条查询语句,默认用;分隔
mysql> select version();show databases;
+-----------+
| version() |
+-----------+
| 8.0.26    |
+-----------+
1 row in set (0.00 sec)

+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysqladmin工具

mysqladmin用于管理mysql服务的本地工具

显示版本信息
bash 复制代码
#客户端版本
[root@mysql ~]# mysqladmin -V
mysqladmin  Ver 8.0.26 for Linux on x86_64 (Source distribution)

#客户端和服务端版本信息
[root@mysql ~]# mysqladmin version 
mysqladmin  Ver 8.0.26 for Linux on x86_64 (Source distribution)
Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Server version          8.0.26
Protocol version        10
Connection              Localhost via UNIX socket
UNIX socket             /var/lib/mysql/mysql.sock
Uptime:                 17 min 36 sec

Threads: 2  Questions: 153  Slow queries: 0  Opens: 234  Flush tables: 3  Open tables: 153  Queries per second avg: 0.144
显示状态信息
bash 复制代码
[root@mysql ~]# mysqladmin status
Uptime: 1105  Threads: 2  Questions: 155  Slow queries: 0  Opens: 234  Flush tables: 3  Open tables: 153  Queries per second avg: 0.140
关闭服务
bash 复制代码
#mysqladmin只能关闭服务,不能启动服务
[root@mysql ~]# mysqladmin shutdown 
[root@mysql ~]# echo $?
0

[root@mysql ~]# systemctl start mysqld.service 
创建数据库和删除数据库
bash 复制代码
#创建
[root@mysql ~]# mysqladmin create db1
[root@mysql ~]# mysqladmin create db2
[root@mysql ~]# mysql -e 'show databases'
+--------------------+
| Database           |
+--------------------+
| db1                |
| db2                |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

#删除
[root@mysql ~]# mysqladmin drop db1
Dropping the database is potentially a very bad thing to do.
Any data stored in the database will be destroyed.

Do you really want to drop the 'db1' database [y/N] `y`
Database "db1" dropped

#强制删除,不需要确认
[root@mysql ~]# mysqladmin -f drop db2
Database "db2" dropped

#验证db1和db2已经删除
[root@mysql ~]# mysql -e 'show databases'
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

SQL 语言

关系型数据库的构成

组件 关键字 说明
数据库 database 表的集合,一个数据库中可以有多个表,在文件系统中表出就是一个目录
table 在数据库中以二维表的形式出现,有行和列,数据库中的数据就是存放于表中的
索引 index 索引通常建立在一个列上,用以加快数据查询速度
视图 view 用SQL语言构建的虚拟表,可以临时把两个或多个表以逻辑关系关联上,对外提供查询
存储过程 procedure 存储过程是一组为了完成特定功能的SQL语句集合,客户端可以直接调用
存储函数 function 存储函数和存储过程一样,都是SQL语句集合,但可以使用参数
触发器 tigger 触发器也是有SQL语句的集合组成,但需要达到触发条件才能调用
事件调度器 event scheduler 数据库中的计划任务
用户 user 连接服务端时的用户名
权限 privilege 每个用户可以对哪些数据库或表进行操作,在什么IP能连接

SQL语言介绍

SQL:(Structured Query Language)结构化查询语言。

语言规范

  • 在数据库系统中,SQL语句不区分大小写,建议用大写。
  • SQL语句可单行或多行书写,默认以 **;**结尾。
  • 关键词不能跨多行或简写。
  • 用空格和TAB缩进来提高语句的可读性。
  • 子句通常位于独立行,便于编辑,提高可读性。

数据库对象和命名

数据库中的组件(对象)

bash 复制代码
数据库、表、索引、视图、用户、存储过程、函数、触发器、事件调度器等

组件命名规则

  • 可以包括字母,数字和三个特殊字符(#_$)
  • 不能使用MySQL的保留字

SQL 语句分类

SQL语句类型 说明 具体语句
DDL Data Defination Language数据定义语言 CREATE,DROP,ALTER
DML Data Mainpulation Language数据操纵语言 INSERT,DELETE,UPDATE
DQL Data Query Language数据查询语言 SELECT
DCL Data Control Language数据控制语言 GRANT,REVOKE
TCL Transaction Control Language事务控制语言 BEGIN,COMMIT,ROLLBACK,SAVEPOINT

SQL 语句构成

mysql 复制代码
mysql> select host,user,authentication_string from mysql.user where authentication_string = '';
+-----------+------+-----------------------+
| host      | user | authentication_string |
+-----------+------+-----------------------+
| localhost | root |                       |
+-----------+------+-----------------------+
1 row in set (0.00 sec)

命令行下查看帮助

mysql 复制代码
mysql> help contents;
You asked for help about help category: "Contents"
For more information, type 'help <item>', where <item> is one of the following
categories:
   Account Management
   Administration
   Components
   Compound Statements
   Contents
   Data Definition
   Data Manipulation
...

#查看DDL帮助
mysql> help data definition         
You asked for help about help category: "Data Definition"
For more information, type 'help <item>', where <item> is one of the following
topics:
   ALTER DATABASE
   ALTER EVENT
   ALTER FUNCTION
   ALTER INSTANCE
   ALTER LOGFILE GROUP
   ALTER PROCEDURE
   ALTER SCHEMA
...

mysql> help create database;
Name: 'CREATE DATABASE'
Description:
Syntax:
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
    [create_option] ...

create_option: [DEFAULT] {
    CHARACTER SET [=] charset_name
  | COLLATE [=] collation_name
  | ENCRYPTION [=] {'Y' | 'N'}
}

CREATE DATABASE creates a database with the given name. To use this
statement, you need the CREATE privilege for the database. CREATE
SCHEMA is a synonym for CREATE DATABASE.

URL: https://dev.mysql.com/doc/refman/8.0/en/create-database.html

排序

查看当前使用的排序规则

bash 复制代码
mysql> show variables like 'collation%';
+----------------------+--------------------+
| Variable_name        | Value              |
+----------------------+--------------------+
| collation_connection | utf8mb4_0900_ai_ci |
| collation_database   | utf8mb4_0900_ai_ci |
| collation_server     | utf8mb4_0900_ai_ci |
+----------------------+--------------------+
3 rows in set (0.02 sec)

生产环境中,使用uf8mb4编码,使用默认排序规则

管理数据库

查看数据库列表

bash 复制代码
#默认这四个系统库,不能删除
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.01 sec)

创建数据库

bash 复制代码
mysql> create database testdb1;
Query OK, 1 row affected (0.00 sec)

#如果已存在,再次创建会报错
mysql> create database testdb1;
ERROR 1007 (HY000): Can't create database 'testdb1'; database exists

#不报错,但也没有创建,if not exists表示如果不存在则创建
mysql> create database if not exists testdb1;
Query OK, 1 row affected, 1 warning (0.00 sec)

#查看数据库列表
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| testdb1            |
+--------------------+
5 rows in set (0.00 sec)

创建数据库,本质上是在硬盘上创建了目录

bash 复制代码
[root@mysql ~]# ls -d /var/lib/mysql/testdb1/
/var/lib/mysql/testdb1/

删除数据库

bash 复制代码
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| testdb1            |
+--------------------+
5 rows in set (0.00 sec)

#删除数据库
mysql> drop database testdb1;
Query OK, 0 rows affected (0.00 sec)

#删除不存在的库
mysql> drop database testdb1;
ERROR 1008 (HY000): Can't drop database 'testdb1'; database doesn't exist

#加if exists判断
mysql> DROP DATABASE IF EXISTS testdb2;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

#testdb1对应的目录已不存在
[root@mysql ~]# ls -d /var/lib/mysql/testdb1/
ls: cannot access '/var/lib/mysql/testdb1/': No such file or directory

mysqladmin命令也可以创建和删除数据库

bash 复制代码
#创建数据库db1
[root@mysql ~]# mysqladmin create db1

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| db1                |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

数据类型

MySQL 中定义数据字段的类型对你数据库的优化是非常重要的。

MySQL 支持多种类型,大致可以分为三类:数值、日期/时间和字符串(字符)类型。

对于任何一个数据表,每一行的每一列对应的元素都是下列数据类型的一种。

类型 关键字
整数类型 TINYINT SMALLINT MEDIUMINT INT (INTEGER) BIGINT
浮点类型 FLOAT DOUBLE
定点数类型 DECIMAL
位类型 BIT
日期时间类型 YEAR TIME DATE DATETIME TIMESTAMP
文本字符串类型 CHAR VARCHAR TINYTEXT TEXT MEDIUMTEXT LONGTEXT
枚举类型 ENUM
集合类型 SET
二进制字符串类型 BINARY VARBINARY TINYBLOB BLOB MEDIUMBLOB LONGBLOB
JSON 类型 JSON对象 JSON 数组
空间数据类型 (单值类型) GEOMETRY POINT LINESTRING POLYGON
空间数据类型 (集合类型) MULTIPOINT MULTILINESTRING MULTIPOLYGON GEOMETRYCOLLECTION

在常见数据表时,除了可以指定列的数据类型,还可以指定列的属性。

关键字 含义
NULL 数据列可包含 NULL 值
NOT NULL 数据列不允许包含 NULL 值
DEFAULT 默认值
PRIMARY KEY 主键
AUTO_INCREMENT 自动递增,适用于整数类型
UNSIGNED 无符号
CHARACTER SET name 指定一个字符集

DDL 语句

DDL语句主要用来操作数据库中的表。

同一个库中不同表可以使用不同的存储引擎,但建议使用同一种存储引擎。

创建表

mysql 复制代码
#选择数据库
mysql> use db1
Database changed

#创建表
mysql> CREATE TABLE student (
    -> id int UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    -> name VARCHAR(20) NOT NULL,
    -> age tinyint UNSIGNED,
    -> #height DECIMAL(5,2),
    -> gender ENUM('M','F') default 'M'
    -> )ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4;
Query OK, 0 rows affected (0.01 sec)

#查看
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| student       |
+---------------+
1 row in set (0.00 sec)

#查看结构
mysql> desc student;
+--------+------------------+------+-----+---------+----------------+
| Field  | Type             | Null | Key | Default | Extra          |
+--------+------------------+------+-----+---------+----------------+
| id     | int unsigned     | NO   | PRI | NULL    | auto_increment |
| name   | varchar(20)      | NO   |     | NULL    |                |
| age    | tinyint unsigned | YES  |     | NULL    |                |
| gender | enum('M','F')    | YES  |     | M       |                |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

#插入一条数据
mysql> insert student (name,age)values('xiaoming',20);
Query OK, 1 row affected (0.01 sec)

#查询表中的所有数据
mysql> select * from student;
+----+----------+------+--------+
| id | name     | age  | gender |
+----+----------+------+--------+
| 10 | xiaoming |   20 | M      |
+----+----------+------+--------+
1 row in set (0.00 sec)

#再次插入一条数据
mysql> insert student(name,age,gender)values('xiaohong',18,'f');
Query OK, 1 row affected (0.00 sec)

mysql> select * from student;
+----+----------+------+--------+
| id | name     | age  | gender |
+----+----------+------+--------+
| 10 | xiaoming |   20 | M      |
| 11 | xiaohong |   18 | F      |
+----+----------+------+--------+
2 rows in set (0.00 sec)

通过查询现存表创建,新表会被直接插入查询而来的数据

bash 复制代码
#查询其他表创建
mysql> create table student2 select name,age from student;
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

#查看
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| student       |
| student2      |
+---------------+
2 rows in set (0.00 sec)

#数据也复制过来了
mysql> select * from student2;
+----------+------+
| name     | age  |
+----------+------+
| xiaoming |   20 |
| xiaohong |   18 |
+----------+------+
2 rows in set (0.01 sec)

通过复制现存的表的表结构创建,但不复制数据

mysql 复制代码
mysql> create table student3 like student;
Query OK, 0 rows affected (0.01 sec)

mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| student       |
| student2      |
| student3      |
+---------------+
3 rows in set (0.00 sec)

mysql> select * from student3;
Empty set (0.00 sec)

查看表

列出数据库中的表
bash 复制代码
#查看当前库中所有表
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| student       |
| student2      |
| student3      |
+---------------+
3 rows in set (0.00 sec)

#查看指定库中的表
mysql> show tables from db1;
+---------------+
| Tables_in_db1 |
+---------------+
| student       |
| student2      |
| student3      |
+---------------+
3 rows in set (0.00 sec)
查看表结构
bash 复制代码
mysql> desc student;
+--------+------------------+------+-----+---------+----------------+
| Field  | Type             | Null | Key | Default | Extra          |
+--------+------------------+------+-----+---------+----------------+
| id     | int unsigned     | NO   | PRI | NULL    | auto_increment |
| name   | varchar(20)      | NO   |     | NULL    |                |
| age    | tinyint unsigned | YES  |     | NULL    |                |
| gender | enum('M','F')    | YES  |     | M       |                |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
查看表状态
bash 复制代码
mysql> show table status like 'student';
+---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
| Name    | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time         | Update_time         | Check_time | Collation          | Checksum | Create_options | Comment |
+---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
| student | InnoDB |      10 | Dynamic    |    2 |           8192 |       16384 |               0 |            0 |         0 |             12 | 2025-12-24 19:31:45 | 2025-12-24 19:34:01 | NULL       | utf8mb4_0900_ai_ci |     NULL |                |         |
+---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
1 row in set (0.00 sec)

mysql> show table status like 'student'\G;
*************************** 1. row ***************************
           Name: student
         Engine: InnoDB
        Version: 10
     Row_format: Dynamic
           Rows: 2
 Avg_row_length: 8192
    Data_length: 16384
Max_data_length: 0
   Index_length: 0
      Data_free: 0
 Auto_increment: 12
    Create_time: 2025-12-24 19:31:45
    Update_time: 2025-12-24 19:34:01
     Check_time: NULL
      Collation: utf8mb4_0900_ai_ci
       Checksum: NULL
 Create_options: 
        Comment: 
1 row in set (0.00 sec)

ERROR: 
No query specified

#不能有库名
mysql> show table status like 'db1.student'\G
Empty set (0.00 sec)
查看库中所有表状态
bash 复制代码
mysql> show table status from db1\G
*************************** 1. row ***************************
           Name: student
         Engine: InnoDB
        Version: 10
     Row_format: Dynamic
           Rows: 2
 Avg_row_length: 8192
    Data_length: 16384
Max_data_length: 0
   Index_length: 0
      Data_free: 0
...

修改和删除表

修改表
bash 复制代码
#修改表名
mysql> alter table student rename stu;
Query OK, 0 rows affected (0.01 sec)

mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| stu           |
| student2      |
| student3      |
+---------------+
3 rows in set (0.01 sec)

#添加表字段
mysql> alter table stu add phone varchar(11) after name;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

#修改字段类型
mysql> alter table stu modify phone int;
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

#修改字段名称和类型
mysql> alter table stu change column phone mobile char(11);
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

#删除字段
mysql> alter table stu drop column mobile;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

#设置字段默认值
mysql> alter table stu alter column gender set default 'M';
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0
bash 复制代码
mysql> create table stu2 select * from stu;
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> desc stu2;
+--------+------------------+------+-----+---------+-------+
| Field  | Type             | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+-------+
| id     | int unsigned     | NO   |     | 0       |       |
| name   | varchar(20)      | NO   |     | NULL    |       |
| age    | tinyint unsigned | YES  |     | NULL    |       |
| gender | enum('M','F')    | YES  |     | M       |       |
+--------+------------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

#添加主键
mysql> alter table stu2 add primary key (id);
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc stu2;
+--------+------------------+------+-----+---------+-------+
| Field  | Type             | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+-------+
| id     | int unsigned     | NO   | PRI | 0       |       |
| name   | varchar(20)      | NO   |     | NULL    |       |
| age    | tinyint unsigned | YES  |     | NULL    |       |
| gender | enum('M','F')    | YES  |     | M       |       |
+--------+------------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

#删除主键
mysql> alter table stu2 drop primary key;
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> desc stu2;
+--------+------------------+------+-----+---------+-------+
| Field  | Type             | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+-------+
| id     | int unsigned     | NO   |     | 0       |       |
| name   | varchar(20)      | NO   |     | NULL    |       |
| age    | tinyint unsigned | YES  |     | NULL    |       |
| gender | enum('M','F')    | YES  |     | M       |       |
+--------+------------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
删除表
bash 复制代码
mysql> show tables
    -> ;
+---------------+
| Tables_in_db1 |
+---------------+
| stu           |
| stu2          |
| student2      |
| student3      |
+---------------+
4 rows in set (0.00 sec)

mysql> drop table student2;drop table db1.student3;
Query OK, 0 rows affected (0.01 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| stu           |
| stu2          |
+---------------+
2 rows in set (0.00 sec)

DML 语句

DML语句包括INSERT,UDPATE,DELETE

插入数据

INSERT可以一次往表中插入一条或多条记录

bash 复制代码
mysql> select * from stu;
+----+----------+------+--------+
| id | name     | age  | gender |
+----+----------+------+--------+
| 10 | xiaoming |   20 | M      |
| 11 | xiaohong |   18 | F      |
+----+----------+------+--------+
2 rows in set (0.00 sec)

#给出所有字段值
mysql> insert into stu values(12,'xiaoli',19,'F');
Query OK, 1 row affected (0.00 sec)

#只给出部分字段值,有些字段值有默认值
mysql> insert into stu(name,age)values('xiaozhou',20);
Query OK, 1 row affected (0.00 sec)

#一次插入多条
mysql> insert into stu (name,age)values('test1',20),('test2',21);
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

#查看
mysql> select * from stu;
+----+----------+------+--------+
| id | name     | age  | gender |
+----+----------+------+--------+
| 10 | xiaoming |   20 | M      |
| 11 | xiaohong |   18 | F      |
| 12 | xiaoli   |   19 | F      |
| 13 | xiaozhou |   20 | M      |
| 14 | test1    |   20 | M      |
| 15 | test2    |   21 | M      |
+----+----------+------+--------+
6 rows in set (0.00 sec)

#如果记录不存在就新增,如果存在就更新
mysql> select * from stu where id=12;
+----+--------+------+--------+
| id | name   | age  | gender |
+----+--------+------+--------+
| 12 | xiaoli |   19 | F      |
+----+--------+------+--------+
1 row in set (0.00 sec)

#将查询结果当值插入
mysql> insert into stu (name,age,gender) select name,age,gender from stu where id=11;
Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> select * from stu;
+----+----------+------+--------+
| id | name     | age  | gender |
+----+----------+------+--------+
| 10 | xiaoming |   20 | M      |
| 11 | xiaohong |   18 | F      |
| 12 | xiaoli   |   19 | F      |
| 13 | xiaozhou |   20 | M      |
| 14 | test1    |   20 | M      |
| 15 | test2    |   21 | M      |
| 16 | xiaohong |   18 | F      |
+----+----------+------+--------+
7 rows in set (0.00 sec)

更新数据

更新数据一定要加条件限制,没有条件则会更新表中所有记录。

bash 复制代码
#不加条件表示更新所有
mysql> update stu set age=30,gender='F';
Query OK, 7 rows affected (0.00 sec)
Rows matched: 7  Changed: 7  Warnings: 0

mysql> select * from stu;
+----+----------+------+--------+
| id | name     | age  | gender |
+----+----------+------+--------+
| 10 | xiaoming |   30 | F      |
| 11 | xiaohong |   30 | F      |
| 12 | xiaoli   |   30 | F      |
| 13 | xiaozhou |   30 | F      |
| 14 | test1    |   30 | F      |
| 15 | test2    |   30 | F      |
| 16 | xiaohong |   30 | F      |
+----+----------+------+--------+
7 rows in set (0.00 sec)

#根据条件更新
mysql> update  stu set age=31 where id>15;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from stu;
+----+----------+------+--------+
| id | name     | age  | gender |
+----+----------+------+--------+
| 10 | xiaoming |   30 | F      |
| 11 | xiaohong |   30 | F      |
| 12 | xiaoli   |   30 | F      |
| 13 | xiaozhou |   30 | F      |
| 14 | test1    |   30 | F      |
| 15 | test2    |   30 | F      |
| 16 | xiaohong |   31 | F      |
+----+----------+------+--------+
7 rows in set (0.00 sec)

#多个条件,满足任何一个条件都更新 OR 可以写成 ||
mysql> update stu set age=21,gender='M' where (id=15 or name is null);
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from stu;
+----+----------+------+--------+
| id | name     | age  | gender |
+----+----------+------+--------+
| 10 | xiaoming |   30 | F      |
| 11 | xiaohong |   30 | F      |
| 12 | xiaoli   |   30 | F      |
| 13 | xiaozhou |   30 | F      |
| 14 | test1    |   30 | F      |
| 15 | test2    |   21 | M      |
| 16 | xiaohong |   31 | F      |
+----+----------+------+--------+
7 rows in set (0.00 sec)

#多个条件满足,AND 可以写成 &&
mysql> update stu set age=22,gender='M' where (id=17 and name is null); 
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0  Changed: 0  Warnings: 0

mysql> select * from stu;                                              
+----+----------+------+--------+
| id | name     | age  | gender |
+----+----------+------+--------+
| 10 | xiaoming |   30 | F      |
| 11 | xiaohong |   30 | F      |
| 12 | xiaoli   |   30 | F      |
| 13 | xiaozhou |   30 | F      |
| 14 | test1    |   30 | F      |
| 15 | test2    |   21 | M      |
| 16 | xiaohong |   31 | F      |
+----+----------+------+--------+
7 rows in set (0.00 sec)

保证无法在没有条件的情况下更新所有

bash 复制代码
[root@mysql ~]# mysql -U

#该配置还可以写到配置文件中
[root@mysql ~]# vim /etc/my.cnf.d/client.cnf
[client]
safe-updates

#无法完全更新
mysql> update stu set age=22;
ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column. 

#必须要指定主键
mysql> update stu set age=23 where id=14;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from stu;
+----+----------+------+--------+
| id | name     | age  | gender |
+----+----------+------+--------+
| 10 | xiaoming |   30 | F      |
| 11 | xiaohong |   30 | F      |
| 12 | xiaoli   |   30 | F      |
| 13 | xiaozhou |   30 | F      |
| 14 | test1    |   23 | F      |
| 15 | test2    |   21 | M      |
| 16 | xiaohong |   31 | F      |
+----+----------+------+--------+
7 rows in set (0.00 sec)

删除数据

bash 复制代码
#查看全部数据
mysql> select * from stu;
+----+----------+------+--------+
| id | name     | age  | gender |
+----+----------+------+--------+
| 10 | xiaoming |   30 | F      |
| 11 | xiaohong |   30 | F      |
| 12 | xiaoli   |   30 | F      |
| 13 | xiaozhou |   30 | F      |
| 14 | test1    |   23 | F      |
| 15 | test2    |   21 | M      |
| 16 | xiaohong |   31 | F      |
+----+----------+------+--------+
7 rows in set (0.00 sec)

#根据条件删除
mysql> delete  from stu where id=10;
Query OK, 1 row affected (0.00 sec)

mysql> select * from stu;
+----+----------+------+--------+
| id | name     | age  | gender |
+----+----------+------+--------+
| 11 | xiaohong |   30 | F      |
| 12 | xiaoli   |   30 | F      |
| 13 | xiaozhou |   30 | F      |
| 14 | test1    |   23 | F      |
| 15 | test2    |   21 | M      |
| 16 | xiaohong |   31 | F      |
+----+----------+------+--------+
6 rows in set (0.00 sec)

在直实生产环境中,一般不会对数据做物理删除,而是用字段来标记为逻辑删除,将对应字段值设为某个特定项(is_del ),(is_del=1)认为是己删除

清空表

bash 复制代码
TRUNCATE TABLE tbl_name;   #DDL语句,不支持事务,效率更高
DELETE FROM tbl_name;      #DML语句

DQL 语句

说明

字段显示可以使用别名:col1 AS alias1,col2 AS alias2,...

WHERE子句:指明过滤条件以实现"选择"的功能

过滤条件:布尔型表达式

算术操作符:+,-,*,/,%

比较操作符:=,<=>(相等或都为空),<>,!=(非标准SQL,>,>=,<,<=

范围查询:BETWEEN min_num AND max_num

不连续的查询:IN(element1,element2,...)

空查询:IS NULL,,IS NOT NULL

DISTINCT去除重复行,SELECT DISTINCT gender FROM students;

模糊查询:LIKE使用%表示任意长度的任意字符_表示任意单个字符

RLIKE:正则表达式,索引失效,不建议使用

REGEXP:匹配字符串可用正则表达式书写模式,同上

逻辑操作符:NOT,AND,OR,XOR
GROUPBY:根据指定的条件把查询结果进行"分组"以用于做"聚合"运算

常见聚合函数:count),sum(),max(),min(),avg(),注意:聚合函数不对null统计

HAVING:对分组聚合运算后的结果指定过滤条件

一旦分组group by,select语句后只跟分组的字段,聚合函数

ORDERBY:根据指定的字段对查询结果进行排序

升序:ASC

降序:DESC

单表操作

查字符串和变量

bash 复制代码
#直接查字符串
mysql> select 123;
+-----+
| 123 |
+-----+
| 123 |
+-----+
1 row in set (0.00 sec)

#指定别名
mysql> select 'wan' as 'xiaowan';
+---------+
| xiaowan |
+---------+
| wan     |
+---------+
1 row in set (0.00 sec)

#查询变量
mysql> select @@port;
+--------+
| @@port |
+--------+
|   3306 |
+--------+
1 row in set (0.00 sec)

#查询函数
mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2025-12-25 13:10:48 |
+---------------------+
1 row in set (0.00 sec)

指定字段和查询条件

bash 复制代码
#查询指定字段
mysql> select id as num from stu;
+-----+
| num |
+-----+
|  11 |
|  12 |
|  13 |
|  14 |
|  15 |
|  16 |
+-----+
6 rows in set (0.00 sec)

#根据条件查询
mysql> select id,name from stu where id=11;
+----+----------+
| id | name     |
+----+----------+
| 11 | xiaohong |
+----+----------+
1 row in set (0.00 sec)

#多条
mysql> select id,name from stu where id in(11,15);
+----+----------+
| id | name     |
+----+----------+
| 11 | xiaohong |
| 15 | test2    |
+----+----------+
2 rows in set (0.00 sec)

#and 可以写为 &&
mysql> select id,name from stu where id>=11 and id <14;
+----+----------+
| id | name     |
+----+----------+
| 11 | xiaohong |
| 12 | xiaoli   |
| 13 | xiaozhou |
+----+----------+
3 rows in set (0.00 sec)

#or 可以写为 ||
mysql> select id,name from stu where id<=12 or id>15;
+----+----------+
| id | name     |
+----+----------+
| 11 | xiaohong |
| 12 | xiaoli   |
| 16 | xiaohong |
+----+----------+
3 rows in set (0.00 sec)

NULL值

bash 复制代码
#null值
mysql> select id,name,age from stu where name is null;
+----+------+------+
| id | name | age  |
+----+------+------+
| 17 | NULL |   23 |
+----+------+------+
1 row in set (0.00 sec)

#非null值
mysql> select id,name,age from stu where name is not null;
+----+----------+------+
| id | name     | age  |
+----+----------+------+
| 11 | xiaohong |   30 |
| 12 | xiaoli   |   30 |
| 13 | xiaozhou |   30 |
| 14 | test1    |   23 |
| 15 | test2    |   21 |
| 16 | xiaohong |   31 |
+----+----------+------+
6 rows in set (0.00 sec)

模糊匹配

bash 复制代码
#以指定字符开头
mysql> select id,name from stu where name like 'x%';
+----+----------+
| id | name     |
+----+----------+
| 11 | xiaohong |
| 12 | xiaoli   |
| 13 | xiaozhou |
| 16 | xiaohong |
+----+----------+
4 rows in set (0.00 sec)

#以指定字符开头
mysql> select id,name from stu where name like 'xiao%';
+----+----------+
| id | name     |
+----+----------+
| 11 | xiaohong |
| 12 | xiaoli   |
| 13 | xiaozhou |
| 16 | xiaohong |
+----+----------+
4 rows in set (0.00 sec)

#以指定字符结尾
mysql> select id,name from stu where name like '%ng';
+----+----------+
| id | name     |
+----+----------+
| 11 | xiaohong |
| 16 | xiaohong |
+----+----------+
2 rows in set (0.00 sec)

#包含指定字符串
mysql> select id,name from stu where name like '%ou%';
+----+----------+
| id | name     |
+----+----------+
| 13 | xiaozhou |
+----+----------+
1 row in set (0.00 sec)

#多个LIKE
mysql> select id,name from stu where name like '%n%' or name like '%i%';
+----+----------+
| id | name     |
+----+----------+
| 11 | xiaohong |
| 12 | xiaoli   |
| 13 | xiaozhou |
| 16 | xiaohong |
+----+----------+
4 rows in set (0.00 sec)

区域间过滤

bash 复制代码
#连续
mysql> select id,name from stu where id between 12 and 15;
+----+----------+
| id | name     |
+----+----------+
| 12 | xiaoli   |
| 13 | xiaozhou |
| 14 | test1    |
| 15 | test2    |
+----+----------+
4 rows in set (0.00 sec)

#取反
mysql> select id,name from stu where id not between 12 and 15;
+----+----------+
| id | name     |
+----+----------+
| 11 | xiaohong |
| 16 | xiaohong |
+----+----------+
2 rows in set (0.00 sec)

#不连续
mysql> select id,name from stu where id in(12,15);
+----+--------+
| id | name   |
+----+--------+
| 12 | xiaoli |
| 15 | test2  |
+----+--------+
2 rows in set (0.00 sec)

#不连续取反
mysql> select id,name from stu where id not in (12,15);
+----+----------+
| id | name     |
+----+----------+
| 11 | xiaohong |
| 13 | xiaozhou |
| 14 | test1    |
| 16 | xiaohong |
+----+----------+
4 rows in set (0.00 sec)

统计和分组

bash 复制代码
#统计表中的记录条数
mysql> select count(*) as total from stu;
+-------+
| total |
+-------+
|     6 |
+-------+
1 row in set (0.01 sec)

#name字段中有null,不统计
mysql> select count(name) from stu;
+-------------+
| count(name) |
+-------------+
|           6 |
+-------------+
1 row in set (0.00 sec)

#最大值,最小值,平均值
mysql> select max(id),min(id),avg(age) from stu;
+---------+---------+----------+
| max(id) | min(id) | avg(age) |
+---------+---------+----------+
|      16 |      11 |  27.5000 |
+---------+---------+----------+
1 row in set (0.00 sec)

#求和
mysql> select sum(age) from stu;
+----------+
| sum(age) |
+----------+
|      165 |
+----------+
1 row in set (0.00 sec)

#分组统计
mysql> select sum(age),gender from stu group by gender;
+----------+--------+
| sum(age) | gender |
+----------+--------+
|      144 | F      |
|       21 | M      |
+----------+--------+
2 rows in set (0.00 sec)

#分组统计
mysql> select count(*),gender from stu group by gender;
+----------+--------+
| count(*) | gender |
+----------+--------+
|        5 | F      |
|        1 | M      |
+----------+--------+
2 rows in set (0.00 sec)

#分组带where条件
mysql> select count(*),max(id),avg(age),gender from stu where name is not null group by gender;
+----------+---------+----------+--------+
| count(*) | max(id) | avg(age) | gender |
+----------+---------+----------+--------+
|        5 |      16 |  28.8000 | F      |
|        1 |      15 |  21.0000 | M      |
+----------+---------+----------+--------+
2 rows in set (0.00 sec)

#分组统计
mysql> select count(*),max(id),avg(age),gender from stu group by gender;
+----------+---------+----------+--------+
| count(*) | max(id) | avg(age) | gender |
+----------+---------+----------+--------+
|        5 |      16 |  28.8000 | F      |
|        1 |      15 |  21.0000 | M      |
+----------+---------+----------+--------+
2 rows in set (0.00 sec)

排序

bash 复制代码
#默认按ID升序排列
mysql> select id,name,age from stu;
+----+----------+------+
| id | name     | age  |
+----+----------+------+
| 11 | xiaohong |   30 |
| 12 | xiaoli   |   30 |
| 13 | xiaozhou |   30 |
| 14 | test1    |   23 |
| 15 | test2    |   21 |
| 16 | xiaohong |   31 |
+----+----------+------+
6 rows in set (0.00 sec)

mysql> select id,name,age from stu order by id;
+----+----------+------+
| id | name     | age  |
+----+----------+------+
| 11 | xiaohong |   30 |
| 12 | xiaoli   |   30 |
| 13 | xiaozhou |   30 |
| 14 | test1    |   23 |
| 15 | test2    |   21 |
| 16 | xiaohong |   31 |
+----+----------+------+
6 rows in set (0.00 sec)

#降序
mysql> select id,name,age from stu order by id desc;
+----+----------+------+
| id | name     | age  |
+----+----------+------+
| 16 | xiaohong |   31 |
| 15 | test2    |   21 |
| 14 | test1    |   23 |
| 13 | xiaozhou |   30 |
| 12 | xiaoli   |   30 |
| 11 | xiaohong |   30 |
+----+----------+------+
6 rows in set (0.00 sec)

去重

bash 复制代码
mysql> select id,name,age from stu order by age desc;
+----+----------+------+
| id | name     | age  |
+----+----------+------+
| 16 | xiaohong |   31 |
| 11 | xiaohong |   30 |
| 12 | xiaoli   |   30 |
| 13 | xiaozhou |   30 |
| 14 | test1    |   23 |
| 15 | test2    |   21 |
+----+----------+------+
6 rows in set (0.00 sec)

#去重
mysql> select distinct age from stu order by age desc;
+------+
| age  |
+------+
|   31 |
|   30 |
|   23 |
|   21 |
+------+
4 rows in set (0.00 sec)

#去重
mysql> select distinct(age) from stu order by age desc;
+------+
| age  |
+------+
|   31 |
|   30 |
|   23 |
|   21 |
+------+
4 rows in set (0.00 sec)

MySQL用户管理

MySQL服务的账户是独立存在的,只用于MySQL服务的登录验证。

虚拟用户:给服务和应用使用的用户账号。

系统用户:Linux系统使用的用户账号

MySQL8.0中默认没有可以远程登陆的用户

无法在远程主机上连接当前主机的MySQL服务

bash 复制代码
mysql> use mysql;
Database changed

mysql> select host,user from user;
+-----------+------------------+
| host      | user             |
+-----------+------------------+
| localhost | mysql.infoschema |
| localhost | mysql.session    |
| localhost | mysql.sys        |
| localhost | root             |
+-----------+------------------+
4 rows in set (0.00 sec)

#现在使用的是第四个
mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

#也可以用status命令来查看
mysql> status
--------------
mysql  Ver 8.0.26 for Linux on x86_64 (Source distribution)

Connection id:          8
Current database:       mysql
Current user:           root@localhost
...

创建用户:CREATE USER

bash 复制代码
mysql> create user test@'192.168.108.%' identified by 'xiaomi';

重命名用户:RENAME USER

bash 复制代码
mysql> rename user test@'192.168.108.%' to test2@'192.168.108.%';

删除用户:DROP USER

bash 复制代码
mysql> drop test@'192.168.108.%';

修改密码

bash 复制代码
#mysql8.0中取消了PASSWORD方法
#MariaDB中还有
mysql> select password('123456');
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('123456')' at line 1

#方式一
#更新密码
mysql> set password for root@'localhost'='123456';
Query OK, 0 rows affected (0.00 sec)

[root@mysql ~]# mysql -uroot -p123456
mysql> 

#方式二
#此方法通用
mysql> alter user root@'localhost' identified by 'xiaomi';
Query OK, 0 rows affected (0.00 sec)

[root@mysql ~]# mysql -uroot -pxiaomi;
mysql> 

#方法三
[root@mysql ~]# mysqladmin -uroot -pxiaomi password 123456
mysqladmin: [Warning] Using a password on the command line interface can be insecure.
Warning: Since password will be sent to server in plain text, use ssl connection to ensure password safety.
[root@mysql ~]# mysql -uroot -p123456
mysql> 

忘记密码

bash 复制代码
#方式一
[root@mysql ~]# vim /etc/my.cnf.d/mysql-server.cnf
[mysqld]
skip-grant-tables
skip-networking          #MYSQL8.0不需要

[root@mysql ~]# systemctl restart mysqld.service
[root@mysql ~]# mysql
mysql>

#步骤1
mysql> update mysql.user set authentication_string='' where user='root' and host='localhost';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

#步骤2
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

#再执行下面命令
mysql> alter user root@'localhost' identified by 'xiaomi';
Query OK, 0 rows affected (0.01 sec)


[root@mysql ~]# vim /etc/my.cnf.d/mysql-server.cnf
[mysqld]
#skip-grant-tables
#skip-grant-tables

[root@mysql ~]# mysql -uroot -pxiaomi
mysql> 

权限管理和DCL语句

在MySQL服务中,新创建的用户仅仅只能连接,没有操作权限,需要配置相应的权限后才能使用。

权限类别

管理类

CREATE USER,FILE,SUPER,SHOW DATABASES,RELOAD,SHUTDOWN,REPLICATION SLAVE,REPLICATION CLIENT,LOCK TABLES,PROCESS,CREATE TEMPORARY TABLES

程序类针对FUNCTION、PROCEDURE、TRIGGER

CREATE,ALTER,DROP,EXCUTE

库和表级别针对DATABASE、TABLE

ALTER,CREATE,CREATE VIEW,DROP INDEX,SHOW VIEW,WITH GRANT OPTION(将自己获得的权限转赠给其他用户)

数据操作

SELECT,INSERT,DELETE,UPDATE

字段级别

SELECT(col1,coI2.,...),UPDATE(col1,col2,...),INSERT(col1,col2,...)

所有权限

ALL PRIVILEGES或ALL

授权

bash 复制代码
#有指定库的所有权限
grant all on wordpress.* to test@'192.168.108.%';

#授予所有权限
grant all on wordpress.* to test@'192.168.108.%' with grant option;

取消权限

bash 复制代码
#取消所有权限
revoke all on *.* from test@'192.168.108.%';

查看用户权限

mysql 复制代码
#查看指定用户权限
show grants for test@'192.168.108.%';

注意

  • MariaDB服务进程启动时会读取mysql库中所有授权表至内存。
  • GRANT或REVOKE等执行权限操作会保存于系统表中,MariaDB的服务进程通常会自动重读授权表,使之生效。
  • 对于不能够或不能及时重读授权表的命令,可手动让MariaDB的服务进程重读授权表:
bash 复制代码
mysql> flush privileges;

mysql的备份与恢复

数据库备份的分类

从物理与逻辑的角度,备份可分为

  • 物理备份:对数据库操作系统的物理文件(如数据文件、日志文件等)的备份
    • 物理备份方法
      • 冷备份(脱机备份):是在关闭数据库的时候进行的
      • 热备份(联机备份):数据库处于运行状态,依赖于数据库的日志文件
      • 温备份:数据库锁定表格(不可写入但可读)的状态下进行备份操作
  • ·逻辑备份:对数据库逻辑组件(如:表等数据库对象)的备份

常见的备份方法

  • 物理冷备
    • 备份时数据库处于关闭状态,直接打包数据库文件
    • 备份速度快,恢复时也是最简单的
  • 专用备份工具mydump或mysqlhotcopy
    • mysqldump常用的逻辑备份工具
    • mysqlhotcopy仅拥有备份MylSAM和ARCHIVE表
  • 启用二进制日志进行增量备份
    • 进行增量备份,需要刷新二进制日志
  • 第三方工具备份
    • 免费的MvSQL热备份软件PerconaXtraBackup

冷备份

bash 复制代码
# 备份(推荐写法)
[root@mysql1 ~]# systemctl stop mysqld
[root@mysql1 ~]# cd /usr/local/mysql/data
#备份
[root@mysql1 data]# mkdir /mysql_bak
[root@mysql1 data]# tar czf /mysql_bak/mysql-backup-$(date +%F).tar.gz *
[root@mysql1 data]# systemctl start mysqld.service
#服务正常
[root@mysql1 data]# mysql -uroot -p123456;
mysql> 

# 删除数据
[root@mysql1 ~]# systemctl stop mysqld.service 
[root@mysql1 ~]# rm -rf /usr/local/mysql/data/*
[root@mysql1 ~]# systemctl start mysqld.service 
[root@mysql1 ~]# systemctl status mysqld.service
#数据库损坏
[root@mysql1 ~]# mysql -uroot -p123456
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

#停止数据库,恢复数据库
[root@mysql1 ~]# systemctl stop mysqld.service 
[root@mysql1 ~]# tar xzf /mysql_bak/mysql-backup-2025-12-25.tar.gz -C /usr/local/mysql/data/
[root@mysql1 ~]# chown -R mysql:mysql /usr/local/mysql/data/
[root@mysql1 ~]# systemctl start mysqld.service
#数据库恢复
[root@mysql1 ~]# mysql -uroot -p123456
mysql> 

逻辑备份

bash 复制代码
#备份数据库
[root@mysql1 ~]# systemctl start mysqld
[root@mysql1 ~]# mysqldump -uroot -p123456 mysql > /mysql_bak/mysql.sql
[root@mysql1 ~]# ls /mysql_bak/mysql.sql 
/mysql_bak/mysql.sql

#备份所有数据库
[root@mysql1 ~]# mysqldump -uroot -p123456 --opt --all-databases > /mysql_bak/all.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.

#备份整个表
[root@mysql1 ~]# mysqldump -uroot -p123456 mysql user > /mysql_bak/user.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.

恢复数据

bash 复制代码
[root@mysql1 ~]# mysql -uroot -p123456
mysql> 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
mysql> show tables;
+---------------------------+
| Tables_in_mysql           |
+---------------------------+
| columns_priv              |
| db                        |
| engine_cost               |
| event                     |
| func                      |
...
| time_zone_transition_type |
| user                      |
+---------------------------+
31 rows in set (0.00 sec)

mysql> drop table user;
Query OK, 0 rows affected (0.00 sec)

mysql> source /mysql_bak/user.sql
Query OK, 0 rows affected (0.00 sec)
...

mysql> show tables;
+---------------------------+
| Tables_in_mysql           |
+---------------------------+
| columns_priv              |
...
| user                      |
+---------------------------+
31 rows in set (0.00 sec)

增量备份

bash 复制代码
[root@mysql1 ~]# vim /etc/my.cnf
#这段下面最后加一行
[mysqld]
log-bin=mysql-bin 

[root@mysql1 ~]# systemctl restart mysqld.service

[root@mysql1 ~]# ls /usr/local/mysql/data/
auto.cnf        ib_logfile0  mysql             performance_schema
ib_buffer_pool  ib_logfile1  mysql-bin.000001  school
ibdata1         ibtmp1       mysql-bin.index   sys


#先进行完整性备份
[root@mysql1 ~]# mysqldump -uroot -p123456 school > /opt/school.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.

#日志刷新生效
[root@mysql1 ~]# mysqladmin -uroot -p123456 flush-logs
mysqladmin: [Warning] Using a password on the command line interface can be insecure.

#新产生的mysql-bin.000002只记录上次刷新后的操作
[root@mysql1 ~]# ls /usr/local/mysql/data/
auto.cnf        ib_logfile0  mysql             mysql-bin.index     sys
ib_buffer_pool  ib_logfile1  mysql-bin.000001  performance_schema
ibdata1         ibtmp1       mysql-bin.000002  school

[root@mysql1 ~]# mysql -uroot -p123456
mysql> use school
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
mysql> select * from info;
+----+-----------+-------+---------+-------+
| id | name      | score | address | hobby |
+----+-----------+-------+---------+-------+
|  1 | 唐三      | 90.00 | 广州    |     1 |
|  2 | 叶凡      | 91.00 | 伦敦    |     2 |
|  3 | 喜羊羊    | 92.00 |         |     3 |
|  4 | 曹操      | 93.00 | 南京    |     4 |
+----+-----------+-------+---------+-------+
4 rows in set (0.00 sec)

#再次插入数据生产增量备份
mysql> insert into info (name,score,address,hobby) values ('美猴王',75,'武汉',1);
Query OK, 1 row affected (0.00 sec)

[root@mysql1 ~]# mysqladmin -uroot -p123456 flush-log
mysqladmin: [Warning] Using a password on the command line interface can be insecure.

#新产生mysql-bin.000003日志记录insert操作
[root@mysql1 ~]# ls /usr/local/mysql/data/
auto.cnf        ib_logfile1       mysql-bin.000002    school
ib_buffer_pool  ibtmp1            mysql-bin.000003    sys
ibdata1         mysql             mysql-bin.index
ib_logfile0     mysql-bin.000001  performance_schema

[root@mysql01 ~]# mysql -uroot -p123456
mysql>

#删除内容
mysql> delete from info where id=5;
Query OK, 1 row affected (0.00 sec)

mysql> select * from info;
+----+-----------+-------+---------+-------+
| id | name      | score | address | hobby |
+----+-----------+-------+---------+-------+
|  1 | 唐三      | 90.00 | 广州    |     1 |
|  2 | 叶凡      | 91.00 | 伦敦    |     2 |
|  3 | 喜羊羊    | 92.00 |         |     3 |
|  4 | 曹操      | 93.00 | 南京    |     4 |
+----+-----------+-------+---------+-------+
4 rows in set (0.00 sec)

#恢复操作,恢复时如果被拒绝,是有其他mysql进程占用了
[root@mysql1 ~]# mysqlbinlog --no-defaults /usr/local/mysql/data/mysql-bin.000003 | mysql -uroot -p123456


#验证
[root@mysql1 ~]# mysql -uroot -p123456
mysql> select * from info;
+----+-----------+-------+---------+-------+
| id | name      | score | address | hobby |
+----+-----------+-------+---------+-------+
|  1 | 唐三      | 90.00 | 广州    |     1 |
|  2 | 叶凡      | 91.00 | 伦敦    |     2 |
|  3 | 喜羊羊    | 92.00 |         |     3 |
|  4 | 曹操      | 93.00 | 南京    |     4 |
|  5 | 美猴王    | 75.00 | 武汉    |     5 |
+----+--------+-------+---------+-------+
5 rows in set (0.00 sec)

主从复制和读写分离

使用目标:数据冗余和灾难恢复;提升并发能力、避免锁冲突。

MySQL读写分离原理

  • 只在主服务器上写,只在从服务器上读

  • 主数据库处理事务性查询,从数据库处理SELECT查询

  • 数据库复制用于将事务性查询的变更同步到集群中的从数据库

  • 读写分离方案

    • 基于程序代码内部实现
    • 基于中间代理层实现
      • MySQL-Proxy
      • Amoeba

实验ip地址

主机名 IP地址 作用
master 192.168.108.101 mysql主服务器
slave1 192.168.108.102 mysql从节点1
slave2 192.168.108.103 mysql从节点2
amoeba 192.168.108.110 amoeba
client 192.168.108.111 应用客户端

时间同步

通过时间戳实现业务的一致性

bash 复制代码
# 所有节点
ntpdate ntp1.aliyun.com
date -R

systemctl disable firewalld --now
setenforce 0

mysql主服务器配置

bash 复制代码
[root@master ~]# vim /etc/my.cnf
[root@master ~]# cat /etc/my.cnf
server-id = 11
log-bin = master-bin
log-slave-updates = true

[root@master ~]# systemctl restart mysqld

[root@master ~]# mysql -u root -p123456
mysql> grant replication slave on *.* to 'myslave'@'192.168.108.%' identified BY '123456';
Query OK, 0 rows affected, 1 warning (0.01 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> show master status;
+-------------------+----------+--------------+------------------+-------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+-------------------+----------+--------------+------------------+-------------------+
| master-bin.000001 |      1102 |              |                  |                   |
+-------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

#检查有没有master-bin.000001
[root@master ~]# ls /usr/local/mysql/data
auto.cnf        ibdata1      ib_logfile1  master-bin.000001  mysql               sys
ib_buffer_pool  ib_logfile0  ibtmp1       master-bin.index   performance_schema

mysql从服务器配置,slave1,slave2都要做如下操作

bash 复制代码
#主从是克隆的要做这个操作,否则UUID一致
[root@slave1 ~]# systemctl stop mysqld
[root@slave1 ~]# rm -f /usr/local/mysql/data/auto.cnf
[root@slave1 ~]# systemctl start mysqld

[root@slave1 ~]# vim /etc/my.cnf
server-id = 22
relay-log = relay-log-bin                         
relay-log-index = slave-relay-bin.index

[root@slave1 ~]# systemctl restart mysqld

[root@slave1 ~]# mysql -u root -p123456
mysql> change master to master_host='192.168.108.101',master_user='myslave',master_password='123456',master_log_file='master-bin.000001',master_log_pos=1102;              #master_log_file,master_log_pos与前面查询的相同
Query OK, 0 rows affected, 2 warnings (0.03 sec)

mysql> start slave;
Query OK, 0 rows affected (0.02 sec)

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.108.101
                  Master_User: myslave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000001
          Read_Master_Log_Pos: 1102
               Relay_Log_File: relay-log-bin.000002
                Relay_Log_Pos: 321
        Relay_Master_Log_File: master-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 1102
              Relay_Log_Space: 526
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 11
                  Master_UUID: 5d895caf-a1e0-11f0-b3ec-000c29866c0f
             Master_Info_File: /usr/local/mysql/data/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl:
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set:
                Auto_Position: 0
         Replicate_Rewrite_DB:
                 Channel_Name:
           Master_TLS_Version:
1 row in set (0.00 sec)

ERROR:
No query specified

#slave2
[root@slave2 ~]# systemctl stop mysqld
[root@slave2 ~]# rm -f /usr/local/mysql/data/auto.cnf
[root@slave2 ~]# systemctl start mysqld

[root@slave2 ~]# vim /etc/my.cnf
server-id = 23
relay-log = relay-log-bin                         
relay-log-index = slave-relay-bin.index

[root@slave2 ~]# systemctl restart mysqld

[root@slave2 ~]# mysql -u root -p123456
mysql> change master to master_host='192.168.108.101',master_user='myslave',master_password='123456',master_log_file='master-bin.000001',master_log_pos=1102;
Query OK, 0 rows affected, 2 warnings (0.04 sec)

mysql> start slave;
Query OK, 0 rows affected (0.01 sec)

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.108.101
                  Master_User: myslave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000001
          Read_Master_Log_Pos: 1102
               Relay_Log_File: relay-log-bin.000002
                Relay_Log_Pos: 321
        Relay_Master_Log_File: master-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 1102
              Relay_Log_Space: 526
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 11
                  Master_UUID: 5d895caf-a1e0-11f0-b3ec-000c29866c0f
             Master_Info_File: /usr/local/mysql/data/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl:
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set:
                Auto_Position: 0
         Replicate_Rewrite_DB:
                 Channel_Name:
           Master_TLS_Version:
1 row in set (0.00 sec)

ERROR:
No query specified

验证主从同步

bash 复制代码
# 主服务器上:
mysql> create database school;
Query OK, 1 row affected (0.01 sec)
mysql> use school;

mysql> create table student (
id int unsigned auto_increment primary key,
name varchar(20) not null,
age tinyint unsigned,
gender enum('M','F') default 'M'
)engine=innodb auto_increment=10 default charset=utf8mb4;

mysql> insert student (name,age)values('路飞',20);

# 去从服务器上 show databases;
mysql> select * from school.student;
+----+--------+------+--------+
| id | name   | age  | gender |
+----+--------+------+--------+
| 10 | 路飞   |   20 | M      |
+----+--------+------+--------+
1 row in set (0.00 sec)

amoeba服务器

bash 复制代码
#普通linux克隆
[root@amoeba ~]# hostnamectl set-hostname amoeba
[root@amoeba ~]# systemctl stop firewalld.service
[root@amoeba ~]# setenforce 0

[root@amoeba ~]# chmod +x jdk-6u14-linux-x64.bin
[root@amoeba ~]# ./jdk-6u14-linux-x64.bin
到yes的时候,输入yes按enter

[root@amoeba ~]# mv jdk1.6.0_14/ /usr/local/jdk1.6

[root@amoeba ~]# vim /etc/profile
最下面加
#java家目录
export JAVA_HOME=/usr/local/jdk1.6  
#类环境和jre
export CLASSPATH=$CLASSPATH:$JAVA_HOME/lib:$JAVA_HOME/jre/lib             
export PATH=$JAVA_HOME/lib:$JAVA_HOME/jre/bin/:$PATH:$HOME/bin 
#指定amoeba路径
export AMOEBA_HOME=/usr/local/amoeba                  
export PATH=$PATH:$AMOEBA_HOME/bin

[root@amoeba ~]# source /etc/profile

[root@amoeba ~]# mkdir /usr/local/amoeba

[root@amoeba ~]# tar zxvf amoeba-mysql-binary-2.2.0.tar.gz -C /usr/local/amoeba/

[root@amoeba ~]# chmod -R 755 /usr/local/amoeba/

#执行结果显示amoeba start|stop说明安装成功
[root@amoeba ~]# /usr/local/amoeba/bin/amoeba
amoeba start|stop

在三台mysql上添加权限开放给amoeba访问

bash 复制代码
#amooba访问数据库的账号 
#master
mysql> grant all on *.* to test@'192.168.108.%' identified by '123.com';

#slave1
mysql> grant all on *.* to test@'192.168.108.%' identified by '123.com';

#slave2
mysql> grant all on *.* to test@'192.168.108.%' identified by '123.com';

回到amoeba服务器

bash 复制代码
[root@amoeba ~]# cd /usr/local/amoeba/
[root@amoeba amoeba]# vim conf/amoeba.xml
---30行--
#客户端访问amoeba账号
 <property name="user">amoeba</property           
----32行---------
#客户端访问ameoba密码
 <property name="password">123456</property>        

---117和120-去掉注释-
 115行 <property name="defaultPool">master</property>
 118行<property name="writePool">master</property>
 119行<property name="readPool">slaves</property>

#数据库配置
[root@amoeba amoeba]# vim conf/dbServers.xml         
---23--注意!!!(mysql5.7,默认没有test数据库所以需要修改为mysql数据库)-(mysql5.5直接忽略)--
<!-- mysql schema -->
<property name="schema">mysql</property>

--26行到30行
 25                         <!-- mysql user -->
 26                         <property name="user">test</property>
 27
 28                         <!--  mysql password -->
 29                         <property name="password">123.com</property>
 30

-----45到50行主服务器地址---
45行<dbServer name="master"  parent="abstractServer">
48行<property name="ipAddress">192.168.108.101</property>
--52到57行从服务器主机名-
52行<dbServer name="slave1"  parent="abstractServer">
--55-从服务器地址-
 <property name="ipAddress">192.168.100.102</property>
 ---52到57行复制一份在58行后面
52行<dbServer name="slave2"  parent="abstractServer">
--55-从服务器地址-
 <property name="ipAddress">192.168.100.103</property>
 
 ---仅跟在上面的配置后面,multiPool行(本来就有,修改)
 <dbServer name="slaves" virtual="true">
 <poolConfig class="com.meidusa.amoeba.server.MultipleServerPool   #不改

<property name="poolNames">slave1,slave2</property>
 </poolConfig>          

[root@amoeba ~]# /usr/local/amoeba/bin/amoeba start&
[1] 21533

[root@amoeba ~]# netstat -anpt | grep java
tcp6       0      0 :::8066                 :::*                    LISTEN      21533/java
tcp6       0      0 127.0.0.1:21128         :::*                    LISTEN      21533/java
tcp6       0      0 192.168.108.110:41754   192.168.108.101:3306    ESTABLISHED 21533/java
tcp6       0      0 192.168.108.110:41722   192.168.108.102:3306    ESTABLISHED 21533/java
tcp6       0      0 192.168.108.110:36956   192.168.108.103:3306    ESTABLISHED 21533/java

测试客户端

bash 复制代码
[root@client ~]# yum install -y mysql
#连接amoeba服务器,8086端口在amoeba上执行netstat -anpt|grep java看
[root@client ~]# mysql -u amoeba -p123456 -h 192.168.108.110 -P8086     
MySQL [(none)]>

MASTER

bash 复制代码
[root@master ~]# mysql -u root -p123456
mysql> use school;
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
mysql> insert student (name,age)values('鸣人',20);
Query OK, 1 row affected (0.00 sec)
#此时会同步

在两台从上

bash 复制代码
# slave1
mysql> stop slave;

# slave2
mysql> stop slave;

在客户端主上,内容不会同步

bash 复制代码
#client上添加,由于不会同步,只有master192.168.108.101节点有该记录
# client
mysql> insert student (name,age)values('卡卡西',30);

在slave1上

bash 复制代码
#slave1
mysql> use school;
mysql> insert student (name,age)values('卡卡西',31);

slave2上

bash 复制代码
# slave2
mysql> use school;
mysql> insert student (name,age)values('卡卡西',32);

验证主从复制

在slave1和slave2上查看

bash 复制代码
# slave1
mysql> select * from student;
+----+-----------+------+--------+
| id | name      | age  | gender |
+----+-----------+------+--------+
| 10 | 路飞      |   20 | M      |
| 11 | 鸣人      |   20 | M      |
| 12 | 卡卡西    |   31 | M      |
+----+-----------+------+--------+
3 rows in set (0.00 sec)

#slave2
mysql> select * from student;
+----+-----------+------+--------+
| id | name      | age  | gender |
+----+-----------+------+--------+
| 10 | 路飞      |   20 | M      |
| 11 | 鸣人      |   20 | M      |
| 12 | 卡卡西    |   32| M      |
+----+-----------+------+--------+
3 rows in set (0.00 sec)

并没有将客户端写入的insert student (name,age)values('卡卡西',30);同步

在mysq-master上查看内容发现写入成功:

bash 复制代码
# master
mysql> select * from student;
+----+-----------+------+--------+
| id | name      | age  | gender |
+----+-----------+------+--------+
| 10 | 路飞      |   20 | M      |
| 11 | 鸣人      |   20 | M      |
| 12 | 卡卡西    |   30 | M      |
+----+-----------+------+--------+
3 rows in set (0.00 sec)

验证读写分离

在客户端上测试,第一次会向从服务器1读数据-第二次会各从2读取

bash 复制代码
#client
MySQL [(none)]> select * from school.student;
+----+-----------+------+--------+
| id | name      | age  | gender |
+----+-----------+------+--------+
| 10 | 路飞      |   20 | M      |
| 11 | 鸣人      |   20 | M      |
| 12 | 卡卡西    |   31 | M      |
+----+-----------+------+--------+
3 rows in set (0.02 sec)

MySQL [(none)]> select * from school.student;
+----+-----------+------+--------+
| id | name      | age  | gender |
+----+-----------+------+--------+
| 10 | 路飞      |   20 | M      |
| 11 | 鸣人      |   20 | M      |
| 12 | 卡卡西    |   32 | M      |
+----+-----------+------+--------+
3 rows in set (0.00 sec)
#都是从从节点读取的,读写分离,由实验结果可知:客户端的读取内容,上从slave1和slave2上轮询得到的。

MHA高可用

  • 传统的MySQL主从架构存在的问题
    • 单点故障

案例前置知识点

  • MHA概述

    • 一套优秀的MySQL高可用环境下故障切换和主从复制的软件
    • MySQL故障过程中,MHA能做到O-30秒内自动完成故障切换
  • MHA的组成

    • MHA Manager(管理节点)
    • MHA Node(数据节点)
  • MHA特点

    • 自动故障切换过程中,MHA试图从宕机的主服务器上保存
    • 二进制日志,最大程度的保证数据不丢失
    • 使用半同步复制,可以大大降低数据丢失的风险
    • 目前MHA支持一主多从架构,最少三台服务,即一主两从

使用场景:自动故障转移(Failover)和主从切换(Switchover)

案例环境

主机名 IP地址 作用
master 192.168.108.131 mysql主服务器,安装node组件
slave1 192.168.108.132 mysql从节点1,安装node组件
slave2 192.168.108.133 mysql从节点2,安装node组件
mha 192.168.108.130 amoeba,安装node组件、manager组件

这里操作系统是 CentOS7 版本,所以这里下载 MHA 版本是 0.57 版本。

案例需求

本案例要求通过 MHA 监控 MySQL 数据库在故障时进行自动切换,不影响业务。

案例实现思路

1) 安装 MySQL 数据库

2) 配置 MySQL 一主两从

3) 安装 MHA 软件

4) 配置无密码认证

5) 配置 MySQL MHA 高可用

6) 模拟 master 故障切换

在三台 MySQL 节点上分别安装前置环境

bash 复制代码
#主从是克隆的要做这个操作,否则UUID一致
[root@slave1 ~]# systemctl stop mysqld
[root@slave1 ~]# rm -f /usr/local/mysql/data/auto.cnf
[root@slave1 ~]# systemctl start mysqld

[root@slave2 ~]# systemctl stop mysqld
[root@slave2 ~]# rm -f /usr/local/mysql/data/auto.cnf
[root@slave2 ~]# systemctl start mysqld

安装编译依赖的环境

bash 复制代码
#master,slave1,slave2配置
[root@master ~]# yum -y install perl-Module-Install
[root@slave1 ~]# yum -y install perl-Module-Install
[root@slave2 ~]# yum -y install perl-Module-Install

修改 Master 的主配置文件/etc/my.cnf 文件

bash 复制代码
[root@master ~]# vim /etc/my.cnf
[mysqld]
server-id = 1                     #三台服务器的 server-id 不能一样
log_bin = master-bin
log-slave-updates = true

配置从服务器:

在/etc/my.cnf 中修改或者增加下面内容。

bash 复制代码
#slave1,请注释/etc/my.cnf 中 [client]下 #default-character-set=utf8
[root@slave1 ~]# vim /etc/my.cnf
server-id = 2           
log_bin = master-bin                
relay-log = relay-log-bin 
relay-log-index = slave-relay-bin.index 

#slave2,请注释/etc/my.cnf 中 [client]下 #default-character-set=utf8
[root@slave2 ~]# vim /etc/my.cnf
server-id = 3                    
relay-log = relay-log-bin 
relay-log-index = slave-relay-bin.index 

三节点都要操作

bash 复制代码
[root@master ~]# ln -s /usr/local/mysql/bin/mysqlbinlog /usr/bin/
[root@master ~]# ln -s /usr/local/mysql/bin/mysql /usr/bin/
[root@master ~]# systemctl restart mysqld

[root@slave1 ~]# ln -s /usr/local/mysql/bin/mysqlbinlog /usr/bin/
[root@slave1 ~]# ln -s /usr/local/mysql/bin/mysql /usr/bin/
[root@slave1 ~]# systemctl restart mysqld

[root@slave2 ~]# ln -s /usr/local/mysql/bin/mysqlbinlog /usr/bin/
[root@slave2 ~]# ln -s /usr/local/mysql/bin/mysql /usr/bin/
[root@slave2 ~]# systemctl restart mysqld

mysql5.7注意

请注释/etc/my.cnf 中 【client】下 #default-character-set=utf8

一定要注释,否则报错

ln -s /usr/local/mysql/bin/mysqlbinlog /usr/bin/

ln -s /usr/local/mysql/bin/mysql /usr/bin/

配置 MySQL 一主两从

MySQL 主从配置相对比较简单。需要注意的是授权。步骤如下:

在所有数据库节点上授权两个用户,一个是从库同步使用,另外一个是 manager 使用。

bash 复制代码
#master
mysql> grant replication slave on *.* to 'myslave'@'192.168.108.%' identified by '123';
mysql> grant all privileges on *.* to 'mha'@'192.168.108.%' identified by 'manager';
mysql> flush privileges;

#slave1
mysql> grant replication slave on *.* to 'myslave'@'192.168.108.%' identified by '123';
mysql> grant all privileges on *.* to 'mha'@'192.168.108.%' identified by 'manager';
mysql> flush privileges;

#slave2
mysql> grant replication slave on *.* to 'myslave'@'192.168.108.%' identified by '123';
mysql> grant all privileges on *.* to 'mha'@'192.168.108.%' identified by 'manager';
mysql> flush privileges;

做案例实验环境时候通过 MHA 检查MySQL 主从有报错,报两个从库通过主机名连接不上主库。

bash 复制代码
#master配置(mha@master与主机名相同)
mysql> grant all privileges on *.* to 'mha'@'master' identified by 'manager';       
mysql> grant all privileges on *.* to 'mha'@'slave1' identified by 'manager';
mysql> grant all privileges on *.* to 'mha'@'slave2' identified by 'manager';
mysql> flush privileges;

#slave1配置(mha@master与主机名相同)
mysql> grant all privileges on *.* to 'mha'@'master' identified by 'manager';       
mysql> grant all privileges on *.* to 'mha'@'slave1' identified by 'manager';
mysql> grant all privileges on *.* to 'mha'@'slave2' identified by 'manager';
mysql> flush privileges;

#slave2配置(mha@master与主机名相同)
mysql> grant all privileges on *.* to 'mha'@'master' identified by 'manager';       
mysql> grant all privileges on *.* to 'mha'@'slave1' identified by 'manager';
mysql> grant all privileges on *.* to 'mha'@'slave2' identified by 'manager';
mysql> flush privileges;

在master主机上查看二进制文件和同步点

bash 复制代码
mysql> show master status;
+-------------------+----------+--------------+------------------+-------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+-------------------+----------+--------------+------------------+-------------------+
| master-bin.000001 |     1634 |              |                  |                   |
+-------------------+----------+--------------+------------------+-------------------+

接下来在 slave1 和 slave2分别执行同步。

bash 复制代码
#slave1
mysql> change master to master_host='192.168.108.131',master_user='myslave',master_password='123',master_log_file='master-bin.000001',master_log_pos=1634; 
mysql> start slave;

#slave2
mysql> change master to master_host='192.168.108.131',master_user='myslave',master_password='123',master_log_file='master-bin.000001',master_log_pos=1634; 
mysql> start slave;

查看 IO 和 SQL 线程都是 yes 代表同步是否正常

mysql 复制代码
#slave1
mysql> show slave status\G;
Slave_IO_Running: Yes
Slave_SQL_Running: Yes

#slave2
mysql> show slave status\G;
Slave_IO_Running: Yes
Slave_SQL_Running: Yes

必须设置两个从库为只读模式:

bash 复制代码
#slave1
mysql> set global read_only=1;

#slave2
mysql> set global read_only=1;

注意:设置完成直接验证主从复制功能

安装 MHA 软件

所有服务器上都安装 MHA 依赖的环境,首先安装 epel 源。

bash 复制代码
#4个节点
# yum install epel-release --nogpgcheck -y

# yum install -y perl-DBD-MySQL \
perl-Config-Tiny \
perl-Log-Dispatch \
perl-Parallel-ForkManager \
perl-ExtUtils-CBuilder \
perl-ExtUtils-MakeMaker \
perl-CPAN

MHA 软件包对于每个操作系统版本不一样,这里 CentOS7.4 必须选择 0.57 版本,

在<注意:所有服务器>上必须先安装 node 组件,最后在 MHA 节点上安装 manager 组件,

manager 依赖 node 组件。

bash 复制代码
#master
[root@master ~]# tar zxvf mha4mysql-node-0.57.tar.gz
[root@master ~]# cd mha4mysql-node-0.57
[root@master ~]# perl Makefile.PL
[root@master ~]# make
[root@master ~]# make install

#slave1
[root@slave1 ~]# tar zxvf mha4mysql-node-0.57.tar.gz
[root@slave1 ~]# cd mha4mysql-node-0.57
[root@slave1 ~]# perl Makefile.PL
[root@slave1 ~]# make
[root@slave1 ~]# make install

#slave2
[root@slave2 ~]# tar zxvf mha4mysql-node-0.57.tar.gz
[root@slave2 ~]# cd mha4mysql-node-0.57
[root@slave2 ~]# perl Makefile.PL
[root@slave2 ~]# make
[root@slave2 ~]# make install

#mha
[root@mha ~]# tar zxvf mha4mysql-node-0.57.tar.gz
[root@mha ~]# cd mha4mysql-node-0.57
[root@mha ~]# perl Makefile.PL
[root@mha ~]# make
[root@mha ~]# make install

在 MHA上安装 manager 组件(一定要先安装node 组件才能安装manager 组件)

bash 复制代码
#mha
[root@mha ~]# tar zxvf mha4mysql-manager-0.57.tar.gz
[root@mha ~]# cd mha4mysql-manager-0.57
[root@mha mha4mysql-manager-0.57]# perl Makefile.PL
[root@mha mha4mysql-manager-0.57]# make
[root@mha mha4mysql-manager-0.57]# make install

manager 安装后在/usr/local/bin 下面会生成几个工具,主要包括以下几个:

masterha_check_ssh 检查 MHA 的 SSH 配置状况

masterha_check_repl 检查 MySQL 复制状况

masterha_manger 启动 manager的脚本

masterha_check_status 检测当前 MHA 运行状态

masterha_master_monitor 检测 master 是否宕机

masterha_master_switch 控制故障转移(自动或者手动)

masterha_conf_host 添加或删除配置的 server 信息

masterha_stop 关闭manager

node 安装后也会在/usr/local/bin 下面会生成几个脚本

save_binary_logs 保存和复制 master 的二进制日志

apply_diff_relay_logs 识别差异的中继日志事件并将其差异的事件应用于其他的 slave

filter_mysqlbinlog 去除不必要的 ROLLBACK 事件(MHA 已不再使用这个工具)

purge_relay_logs 清除中继日志(不会阻塞 SQL 线程)

配置无密码认证

在 manager 上配置到所有数据库节点的无密码认证

bash 复制代码
#一路按回车键
[root@mha ~]# ssh-keygen -t rsa             
[root@mha ~]# ssh-copy-id 192.168.108.131
[root@mha ~]# ssh-copy-id 192.168.108.132
[root@mha ~]# ssh-copy-id 192.168.108.133

在 master 上配置到数据库节点slave1和slave2的无密码认证

bash 复制代码
[root@master ~]# ssh-keygen -t rsa
[root@master ~]# ssh-copy-id 192.168.108.132
[root@master ~]# ssh-copy-id 192.168.108.133

在 slave1 上配置到数据库节点master和slave2的无密码认证

bash 复制代码
[root@slave1 ~]# ssh-keygen -t rsa
[root@slave1 ~]# ssh-copy-id 192.168.108.131
[root@slave1 ~]# ssh-copy-id 192.168.108.133

在 slave2 上配置到数据库节点master和slave1的无密码认证

bash 复制代码
[root@slave2 ~]# ssh-keygen -t rsa
[root@slave2 ~]# ssh-copy-id 192.168.108.131
[root@slave2 ~]# ssh-copy-id 192.168.108.132

配置 MHA

在 manager 节点上复制相关脚本到/usr/local/bin 目录。

bash 复制代码
[root@mha ~]# cp -ra /root/mha4mysql-manager-0.57/samples/scripts /usr/local/bin

复制上述的自动切换时 VIP 管理的脚本到/usr/local/bin 目录,这里使用脚本管理 VIP,

bash 复制代码
[root@mha ~]# cp /usr/local/bin/scripts/master_ip_failover /usr/local/bin

修改内容如下:(删除原有内容,直接复制)

bash 复制代码
#复制时 #号间 一段段复制,否则会全部注释
[root@mha ~]# vim /usr/local/bin/master_ip_failover
#!/usr/bin/env perl
use strict;
use warnings FATAL => 'all';

use Getopt::Long;

my (
$command, $ssh_user, $orig_master_host, $orig_master_ip,
$orig_master_port, $new_master_host, $new_master_ip, $new_master_port
);
#############################添加内容部分#########################################
my $vip = '192.168.108.200';
my $brdc = '192.168.108.255';
my $ifdev = 'ens33';
my $key = '1';
my $ssh_start_vip = "/sbin/ifconfig ens33:$key $vip";
my $ssh_stop_vip = "/sbin/ifconfig ens33:$key down";
my $exit_code = 0;
#my $ssh_start_vip = "/usr/sbin/ip addr add $vip/24 brd $brdc dev $ifdev label $ifdev:$key;/usr/sbin/arping -q -A -c 1 -I $ifdev $vip;iptables -F;";
#my $ssh_stop_vip = "/usr/sbin/ip addr del $vip/24 dev $ifdev label $ifdev:$key";
##################################################################################
GetOptions(
'command=s' => \$command,
'ssh_user=s' => \$ssh_user,
'orig_master_host=s' => \$orig_master_host,
'orig_master_ip=s' => \$orig_master_ip,
'orig_master_port=i' => \$orig_master_port,
'new_master_host=s' => \$new_master_host,
'new_master_ip=s' => \$new_master_ip,
'new_master_port=i' => \$new_master_port,
);

exit &main();

sub main {

print "\n\nIN SCRIPT TEST====$ssh_stop_vip==$ssh_start_vip===\n\n";

if ( $command eq "stop" || $command eq "stopssh" ) {

my $exit_code = 1;
eval {
print "Disabling the VIP on old master: $orig_master_host \n";
&stop_vip();
$exit_code = 0;
};
if ($@) {
warn "Got Error: $@\n";
exit $exit_code;
}
exit $exit_code;
}
elsif ( $command eq "start" ) {

my $exit_code = 10;
eval {
print "Enabling the VIP - $vip on the new master - $new_master_host \n";
&start_vip();
$exit_code = 0;
};
if ($@) {
warn $@;
exit $exit_code;
}
exit $exit_code;
}
elsif ( $command eq "status" ) {
print "Checking the Status of the script.. OK \n";
exit 0;
}
else {
&usage();
exit 1;
}
}
sub start_vip() {
`ssh $ssh_user\@$new_master_host \" $ssh_start_vip \"`;
}
# A simple system call that disable the VIP on the old_master
sub stop_vip() {
`ssh $ssh_user\@$orig_master_host \" $ssh_stop_vip \"`;
}

sub usage {
print
"Usage: master_ip_failover --command=start|stop|stopssh|status --orig_master_host=host --orig_master_ip=ip --orig_master_port=port --new_master_host=host --new_master_ip=ip --new_master_port=port\n";
}

创建 MHA 软件目录并拷贝配置文件。

bash 复制代码
[root@mha ~]# mkdir /etc/masterha
[root@mha ~]# cp /root/mha4mysql-manager-0.57/samples/conf/app1.cnf /etc/masterha/
[root@mha ~]# vim /etc/masterha/app1.cnf
#全部删掉,替换
[server default]
manager_log=/var/log/masterha/app1/manager.log
manager_workdir=/var/log/masterha/app1
master_binlog_dir=/usr/local/mysql/data
master_ip_failover_script=/usr/local/bin/master_ip_failover
master_ip_online_change_script=/usr/local/bin/master_ip_online_change
password=manager
ping_interval=1
remote_workdir=/tmp
repl_password=123
repl_user=myslave
secondary_check_script=/usr/local/bin/masterha_secondary_check -s 192.168.108.132 -s 192.168.108.133
shutdown_script=""
ssh_user=root
user=mha

[server1]
hostname=192.168.108.131
port=3306

[server2]
candidate_master=1
check_repl_delay=0
hostname=192.168.108.132
port=3306

[server3]
hostname=192.168.108.133
port=3306

验证配置

测试 ssh 无密码认证,如果正常最后会输出 successfully,如下所示。

bash 复制代码
#检测SSH无密码认证
[root@mha ~]# masterha_check_ssh -conf=/etc/masterha/app1.cnf

#检测下主从复制
[root@mha ~]# masterha_check_repl -conf=/etc/masterha/app1.cnf
MySQL Replicaxtion Health is OK.

第一次配置需要去master上手动开启虚拟IP

bash 复制代码
#注意:第一次配置需要去master上手动开启虚拟IP
[root@master ~]# /sbin/ifconfig ens33:1 192.168.108.200/24

启动 MHA

bash 复制代码
[root@mha ~]# nohup masterha_manager --conf=/etc/masterha/app1.cnf --remove_dead_master_conf --ignore_last_failover < /dev/null > /var/log/masterha/app1/manager.log 2>&1 &
[1] 36457

查看 MHA 状态,可以看到当前的 master 是 master 节点。

bash 复制代码
[root@mha ~]# masterha_check_status --conf=/etc/masterha/app1.cnf
app1 (pid:36457) is running(0:PING_OK), master:192.168.108.131

查看 MHA 日志,也以看到当前的 master 是 192.168.108.131,如下所示。

bash 复制代码
[root@mha ~]# cat /var/log/masterha/app1/manager.log
...
192.168.108.131(192.168.108.131:3306) (current master)
 +--192.168.108.132(192.168.108.132:3306)
 +--192.168.108.133(192.168.108.133:3306)
...

验证

bash 复制代码
#mha节点A窗口操作
[root@mha ~]# tailf /var/log/masterha/app1/manager.log     //启用监控观察日志记录

#master节点操作
[root@master ~]# pkill -9 mysql         //查看master变化,看上面命令的日志

#回到mha节点A窗口观察日志
[root@mha ~]# tailf /var/log/masterha/app1/manager.log

故障修复步骤

  1. 修复db
bash 复制代码
# master 上操作
[root@master ~]# systemctl start mysqld

# 三台mysql执行 show mastart status,show slave status\G;观察现象
#master
mysql> show master status;
+-------------------+----------+--------------+------------------+-------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+-------------------+----------+--------------+------------------+-------------------+
| master-bin.000010 |      1364 |              |                  |                   |
+-------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

mysql> show slave status\G;
Empty set (0.01 sec)

ERROR:
No query specified

mysql>

#slave1
mysql> show master status;
+-------------------+----------+--------------+------------------+-------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+-------------------+----------+--------------+------------------+-------------------+
| master-bin.000001 |     1894 |              |                  |                   |
+-------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.108.131
                  Master_User: myslave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000010
          Read_Master_Log_Pos: 1364
...
          Exec_Master_Log_Pos: 1364
...

#slave2
mysql> show master status;
Empty set (0.00 sec)

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.108.131
                  Master_User: myslave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000010
          Read_Master_Log_Pos: 1364
...
          Exec_Master_Log_Pos: 1364
...
  1. 修复主从

让slave01(备用master)成为master,让原master变成slave01

bash 复制代码
# master操作
change master to master_host='192.168.108.132',master_user='myslave',master_password='123',master_log_file='master-bin.000001',master_log_pos=1894;       #这里的master_log_pos写mysql2的
start slave;

继续查看

bash 复制代码
#master
mysql> show master status;
+-------------------+----------+--------------+------------------+-------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+-------------------+----------+--------------+------------------+-------------------+
| master-bin.000010 |      1364 |              |                  |                   |
+-------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.108.132
                  Master_User: myslave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000001
          Read_Master_Log_Pos: 1894
...
          Exec_Master_Log_Pos: 1894
...

#slave1
mysql> show master status;
+-------------------+----------+--------------+------------------+-------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+-------------------+----------+--------------+------------------+-------------------+
| master-bin.000001 |     1894 |              |                  |                   |
+-------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

mysql>
mysql> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.108.131
                  Master_User: myslave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: master-bin.000010
          Read_Master_Log_Pos: 1364
...
          Exec_Master_Log_Pos: 1364
...
相关推荐
数据皮皮侠2 小时前
2m气温数据集(1940-2024)
大数据·数据库·人工智能·制造·微信开放平台
QT 小鲜肉2 小时前
【Linux命令大全】001.文件管理之mmove命令(实操篇)
linux·服务器·前端·chrome·笔记
不会学习?2 小时前
markdown笔记分享
经验分享·笔记
Psycho_MrZhang2 小时前
Redis 设计思想总结
数据库·redis·缓存
QT 小鲜肉3 小时前
【Linux命令大全】001.文件管理之mdel命令(实操篇)
linux·运维·服务器·chrome·笔记
曹牧3 小时前
Java:Assert.isTrue()
java·前端·数据库
程序员葫芦娃4 小时前
【Java毕设项目】基于SSM的旅游资源网站
java·开发语言·数据库·编程·课程设计·旅游·毕设
2401_865854884 小时前
怎样挑选适合业务的数据库云服务?
数据库
lkbhua莱克瓦244 小时前
基础-函数
开发语言·数据库·笔记·sql·mysql·函数