32-38-Linux学习之旅之MySQL综合

Linux学习之旅之MySQL基础

一、数据结构

类型 定义 典型格式 例子 存储方式 特点
结构化数据 有固定预定义模式,严格二维表结构,字段清晰 数据库表 MySQL、Oracle 表,Excel 规整表格,业务台账 关系型数据库 RDBMS 字段固定,可直接 SQL 查询,易统计分析
半结构化数据 没有严格表结构,但自带标记 / 标签,有层级,数据结构可变 JSON、XML、YAML、CSV(不规整)、Parquet 日志、接口返回 JSON,配置文件,MongoDB 文档 MongoDB、HDFS、对象存储、数仓 没有固定表 schema,字段可动态增减,需要解析提取字段
非结构化数据 无固定结构,没有可直接解析的字段标签 二进制、文本流 图片、视频、音频、PDF、Word 文档、聊天记录 对象存储 S3、NAS、HDFS 不能直接用 SQL 读取,需要 AI / 工具解析提取信息,占数据总量绝大部分

二、数据库基础知识

1、数据库相关概念

DB(Database,数据库)

bash 复制代码
# 存放数据的仓库,是数据的集合。

# 按照一定数据模型组织、存储在一起的相关数据集合,是实实在在的数据。

# 例子:MySQL 里的hisdb、student_db,就是 DB;一堆表、索引、视图合起来叫数据库。

# 本质:数据本身。

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

bash 复制代码
#管理数据库的软件系统,介于用户和 DB 之间。

#用来创建、操作、维护数据库的一套软件,是核心工具。

#例子:MySQL、Oracle、SQL Server、PostgreSQL、MongoDB 都属于 DBMS。

#功能:建库建表、增删改查、权限控制、备份恢复、事务、索引、并发控制。

#本质:管理数据的软件。

#关系:我们通过 DBMS 软件 去操作里面的 DB(数据库 / 数据)。

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

bash 复制代码
#人,数据库运维管理人员。

#负责数据库环境部署、调优、备份恢复、故障处理、权限管理、容量规划、安全审计。

#日常工作:安装升级 DBMS、监控数据库性能、RMAN 备份、慢 SQL 优化、故障排查、用户账号权限管理、灾备演练。

#本质:岗位 / 人员。

2、数据库安装(安装前做好快照)

apt或dnf安装

bash 复制代码
$查看仓库列表
root@ubuntu2404ser:~#  apt list mysql-server
Listing... Done
mysql-server/noble-security,noble-updates,noble-updates,noble-security 8.0.46-0ubuntu0.24.04.3 all
N: There is 1 additional version. Please use the '-a' switch to see it

#下载MySQL并自动安装
root@ubuntu2404ser:~# apt install mysql-server -y
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done

#查看服务运行状态
root@ubuntu2404ser:~# systemctl status mysql.service
● mysql.service - MySQL Community Server
     Loaded: loaded (/usr/lib/systemd/system/mysql.service; enabled; preset: enabled)
     Active: active (running) since Tue 2026-08-25 00:53:35 UTC; 28s ago
    Process: 2994 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
   Main PID: 3003 (mysqld)
     Status: "Server is operational"
      Tasks: 38 (limit: 2130)
     Memory: 363.8M (peak: 378.2M)
        CPU: 2.120s
     CGroup: /system.slice/mysql.service
             └─3003 /usr/sbin/mysqld

Aug 25 00:53:33 ubuntu2404ser systemd[1]: Starting mysql.service - MySQL Community Server...
Aug 25 00:53:35 ubuntu2404ser systemd[1]: Started mysql.service - MySQL Community Server.

#登录数据库默认用户root,密码空
root@ubuntu2404ser:~# mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.46-0ubuntu0.24.04.3 (Ubuntu)

Copyright (c) 2000, 2026, 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.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

#查看当前数据库的版本信息
mysql> select version();
+-------------------------+
| version()               |
+-------------------------+
| 8.0.46-0ubuntu0.24.04.3 |
+-------------------------+
1 row in set (0.00 sec)


#退出
mysql> exit;
Bye

源安装

bash 复制代码
#创建官方源下载文件存放路径
root@ubuntu2404ser:~# mkdir -p /data/softs
root@ubuntu2404ser:~# cd /data/softs

#下载官方源文件包
root@ubuntu2404ser:/data/softs# wget https://dev.mysql.com/get/mysql-apt-config_0.8.40-1_all.deb
--2026-08-25 01:04:53--  https://dev.mysql.com/get/mysql-apt-config_0.8.40-1_all.deb
Resolving dev.mysql.com (dev.mysql.com)... 173.222.146.221, 2600:1417:76:58b::2e31, 2600:1417:76:589::2e31
Connecting to dev.mysql.com (dev.mysql.com)|173.222.146.221|:443... connected.
HTTP request sent, awaiting response... 302 Moved Temporarily
Location: https://repo.mysql.com//mysql-apt-config_0.8.40-1_all.deb [following]

#从看看并安装
root@ubuntu2404ser:/data/softs# ls
mysql-apt-config_0.8.40-1_all.deb
root@ubuntu2404ser:/data/softs# dpkg -i mysql-apt-config_0.8.40-1_all.deb
Selecting previously unselected package mysql-apt-config.
(Reading database ... 87927 files and directories currently installed.)
Preparing to unpack mysql-apt-config_0.8.40-1_all.deb ...
Unpacking mysql-apt-config (0.8.40-1) ...
Setting up mysql-apt-config (0.8.40-1) ...
root@ubuntu2404ser:/data/softs# apt update

#添加官方源
bash 复制代码
#更新源仓库
root@ubuntu2404ser:/data/softs# apt update
Hit:1 http://mirrors.aliyun.com/ubuntu noble InRelease
Hit:3 http://mirrors.aliyun.com/ubuntu noble-security InRelease

#查看仓库列表
root@ubuntu2404ser:/data/softs# apt list mysql-community-server mysql-community-client
Listing... Done
mysql-community-client/unknown 8.4.11-1ubuntu24.04 amd64
mysql-community-server/unknown 8.4.11-1ubuntu24.04 amd64

#下载
root@ubuntu2404ser:/data/softs# apt -y install mysql-community-server
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
bash 复制代码
#查看运行状态
root@ubuntu2404ser:/data/softs# systemctl status mysql.service
● mysql.service - MySQL Community Server
     Loaded: loaded (/usr/lib/systemd/system/mysql.service; enabled; preset: enabled)
     Active: active (running) since Tue 2026-08-25 01:12:24 UTC; 5min ago
       Docs: man:mysqld(8)
             http://dev.mysql.com/doc/refman/en/using-systemd.html
   Main PID: 3041 (mysqld)
     Status: "Server is operational"
      Tasks: 35 (limit: 2130)
     Memory: 420.6M (peak: 434.5M)
        CPU: 7.559s
     CGroup: /system.slice/mysql.service
             └─3041 /usr/sbin/mysqld

Aug 25 01:12:22 ubuntu2404ser systemd[1]: Starting mysql.service - MySQL Community Server...
Aug 25 01:12:24 ubuntu2404ser systemd[1]: Started mysql.service - MySQL Community Server.
root@ubuntu2404ser:/data/softs#

#登录数据库,-u用户名 -p密码,因安全环境留空下面数密码
root@ubuntu2404ser:/data/softs# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.4.11 MySQL Community Server - GPL

Copyright (c) 2000, 2026, 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.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select version();
+-----------+
| version() |
+-----------+
| 8.4.11    |
+-----------+
1 row in set (0.00 sec)

mysql>
mysql> exit;
Bye

安装9.7版本

bash 复制代码
root@ubuntu2404ser:~# mkdir -p /data/softs
root@ubuntu2404ser:~# cd /data/softs
root@ubuntu2404ser:/data/softs# ls
mysql-apt-config_0.8.40-1_all.deb
root@ubuntu2404ser:/data/softs# dpkg -i mysql-apt-config_0.8.40-1_all.deb
bash 复制代码
root@ubuntu2404ser:/data/softs# apt update
Hit:1 http://mirrors.aliyun.com/ubuntu noble InRelease
Hit:3 http://mirrors.aliyun.com/ubuntu noble-security InRelease
Hit:4 http://mirrors.aliyun.com/ubuntu noble-updates InRelease


root@ubuntu2404ser:/data/softs# apt list mysql-community-server mysql-community-client
Listing... Done
mysql-community-client/unknown 9.7.2-1ubuntu24.04 amd64
mysql-community-server/unknown 9.7.2-1ubuntu24.04 amd64
root@ubuntu2404ser:/data/softs# apt -y install mysql-community-server
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  libmecab2 mecab-ipadic mecab-ipadic-utf8 mecab-utils mysql-client mysql-common

  root@ubuntu2404ser:/data/softs# systemctl status mysql.service
● mysql.service - MySQL Community Server
     Loaded: loaded (/usr/lib/systemd/system/mysql.service; enabled; preset: enabled)
     Active: active (running) since Tue 2026-08-25 01:28:04 UTC; 22s ago
       Docs: man:mysqld(8)
             https://dev.mysql.com/doc/refman/en/using-systemd.html
   Main PID: 2814 (mysqld)
     Status: "Server is operational"
      Tasks: 36 (limit: 2130)
     Memory: 426.7M (peak: 440.7M)
        CPU: 2.989s
     CGroup: /system.slice/mysql.service
             └─2814 /usr/sbin/mysqld

Aug 25 01:28:01 ubuntu2404ser systemd[1]: Starting mysql.service - MySQL Community Server...
Aug 25 01:28:04 ubuntu2404ser systemd[1]: Started mysql.service - MySQL Community Server.
root@ubuntu2404ser:/data/softs# netstat -tnlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name

tcp6       0      0 :::3306                 :::*                    LISTEN      2814/mysqld   
tcp6       0      0 :::33060                :::*                    LISTEN      2814/mysqld   


#-P指定端口号 -h 指定连接数据库地址,本地登录不需要
root@ubuntu2404ser:/data/softs# mysql -uroot -p -P3306 -h localhost
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 14
Server version: 9.7.2 MySQL Community Server - GPL

Copyright (c) 2000, 2026, 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.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select version();
+-----------+
| version() |
+-----------+
| 9.7.2     |
+-----------+
1 row in set (0.001 sec)

mysql>

mariadb安装

bash 复制代码
root@ubuntu2404ser:~# apt list mariadb-server
Listing... Done
mariadb-server/noble-updates,noble-updates 1:10.11.14-0ubuntu0.24.04.1 amd64
N: There are 2 additional versions. Please use the '-a' switch to see them.
root@ubuntu2404ser:~# apt install mariadb-server -y
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  galera-4 libcgi-fast-perl libcgi-pm-perl libclone-perl libconfig-inifiles-perl libdbd-mysql-perl libdbi-perl
  libencode-locale-perl libfcgi-bin libfcgi-perl libfcgi0t64 libhtml-parser-perl libhtml-tagset-perl
 root@ubuntu2404ser:~# systemctl status mariadb
● mariadb.service - MariaDB 10.11.14 database server
     Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; preset: enabled)
     Active: active (running) since Tue 2026-08-25 02:02:06 UTC; 1min 27s ago
       Docs: man:mariadbd(8)
             https://mariadb.com/kb/en/library/systemd/
   Main PID: 2156 (mariadbd)
     Status: "Taking your SQL requests now..."
      Tasks: 10 (limit: 14046)
     Memory: 78.8M (peak: 81.8M)
        CPU: 1.085s
     CGroup: /system.slice/mariadb.service
             └─2156 /usr/sbin/mariadbd

Aug 25 02:02:06 ubuntu2404ser mariadbd[2156]: 2026-08-25  2:02:06 0 [Note] Plugin 'FEEDBACK' is disabled.
Aug 25 02:02:06 ubuntu2404ser mariadbd[2156]: 2026-08-25  2:02:06 0 [Note] InnoDB: Loading buffer pool(s) from /va>
Aug 25 02:02:06 ubuntu2404ser mariadbd[2156]: 2026-08-25  2:02:06 0 [Warning] You need to use --log-bin to make -->
Aug 25 02:02:06 ubuntu2404ser mariadbd[2156]: 2026-08-25  2:02:06 0 [Note] Server socket created on IP: '127.0.0.1>
Aug 25 02:02:06 ubuntu2404ser mariadbd[2156]: 2026-08-25  2:02:06 0 [Note] InnoDB: Buffer pool(s) load completed a>
Aug 25 02:02:06 ubuntu2404ser mariadbd[2156]: 2026-08-25  2:02:06 0 [Note] /usr/sbin/mariadbd: ready for connectio>
Aug 25 02:02:06 ubuntu2404ser mariadbd[2156]: Version: '10.11.14-MariaDB-0ubuntu0.24.04.1'  socket: '/run/mysqld/m>
Aug 25 02:02:06 ubuntu2404ser systemd[1]: Started mariadb.service - MariaDB 10.11.14 database server.
Aug 25 02:02:06 ubuntu2404ser /etc/mysql/debian-start[2171]: Upgrading MariaDB tables if necessary.
Aug 25 02:02:06 ubuntu2404ser /etc/mysql/debian-start[2186]: Triggering myisam-recover for all MyISAM tables and a>

root@ubuntu2404ser:~# netstat -tnlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      643/systemd-resolve
tcp        0      0 127.0.0.54:53           0.0.0.0:*               LISTEN      643/systemd-resolve
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      2156/mariadbd
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1/init
tcp        0      0 127.0.0.1:6010          0.0.0.0:*               LISTEN      1179/sshd: root@pts
tcp6       0      0 :::22                   :::*                    LISTEN      1/init
tcp6       0      0 ::1:6010                :::*                    LISTEN      1179/sshd: root@pts
root@ubuntu2404ser:~# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 31
Server version: 10.11.14-MariaDB-0ubuntu0.24.04.1 Ubuntu 24.04

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)]> select version();
+-----------------------------------+
| version()                         |
+-----------------------------------+
| 10.11.14-MariaDB-0ubuntu0.24.04.1 |
+-----------------------------------+
1 row in set (0.001 sec)

MariaDB [(none)]>

三、命令基础

1、客户端常用命令

命令 作用
\h 查看帮助
\s 查看数据库连接状态、版本、字符集、端口
use 库名; 切换数据库 use hisdb;
show databases; 查看所有数据库
show tables; 查看当前库下所有表
show tables from 库名; 不切换库,直接看别的库的表
desc 表名; / describe 表名; 查看表结构
show create table 表名\G 查看建表语句,\G垂直展示,不要加分号
show create database 库名; 查看建库语句
show processlist; 查看当前数据库连接线程
show variables like '%char%'; 查看字符集相关参数
source /xxx/xxx.sql; 执行导入 sql 脚本(本地文件)
\. /xxx/xxx.sql 等价 source,导入脚本
exit; / quit; / \q 退出 mysql 客户端
\c 取消当前输入的语句,放弃执行
-r 重新连接服务端
\! 在数据库使用系统命令
bash 复制代码
mysql> \s
--------------
mysql  Ver 8.0.46 for Linux on x86_64 (MySQL Community Server - GPL)

Connection id:          8
Current database:
Current user:           root@localhost
SSL:                    Not in use
Current pager:          stdout
Using outfile:          ''
Using delimiter:        ;
Server version:         8.0.46 MySQL Community Server - GPL
Protocol version:       10
Connection:             Localhost via UNIX socket
Server characterset:    utf8mb4
Db     characterset:    utf8mb4
Client characterset:    utf8mb4
Conn.  characterset:    utf8mb4
UNIX socket:            /var/run/mysqld/mysqld.sock
Binary data as:         Hexadecimal
Uptime:                 5 min 14 sec

Threads: 2  Questions: 5  Slow queries: 0  Opens: 119  Flush tables: 3  Open tables: 38  Queries per second avg: 0.015
--------------

mysql> \r
Connection id:    9
Current database: *** NONE ***

mysql> \! hostname
ubuntu2404ser

2、命令规范

bash 复制代码
- 在数据库系统中,SQL 语句不区分大小写,建议用大写。

- SQL语句可单行或多行书写,默认以 " ; " 结尾。

- 关键词不能跨多行或简写。

- 用空格和TAB 缩进来提高语句的可读性。

- 子句通常位于独立行,便于编辑,提高可读性。

- 在 SQL 中,特别是在 MySQL 和 MariaDB 这样的数据库系统中,@@ 前缀用于访问系统变量(system variables)。系统变量是数据库服务器在运行时维护的一组值,这些值可以影响服务器的操作或提供有关服务器状态的信息。
bash 复制代码
mysql> select @@hostname;
+---------------+
| @@hostname    |
+---------------+
| ubuntu2404ser |
+---------------+
1 row in set (0.00 sec)

mysql> SelEct @@hostname;
+---------------+
| @@hostname    |
+---------------+
| ubuntu2404ser |
+---------------+
1 row in set (0.01 sec)

mysql>

#习惯可以将系统命令大写,其他参数小写
mysql> SELECT * FROM mysql.user;

3、SQL语句类型

类别 英文全称 中文名称 作用 核心关键字
DDL Data Definition Language 数据定义语言 操作库、表、索引、视图 等对象结构 CREATEALTERDROPTRUNCATERENAME
DML Data Manipulation Language 数据操纵语言 操作表里面行数据 INSERTUPDATEDELETE
DQL Data Query Language 数据查询语言 查询数据 SELECT
DCL Data Control Language 数据控制语言 用户创建、权限管理 CREATE USERGRANTREVOKE
TCL Transaction Control Language 事务控制语言 管理事务 START TRANSACTIONCOMMITROLLBACKSAVEPOINT

4、查看数据库

bash 复制代码
查看数据库

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


查看库详情
mysql> show create database db1\G
*************************** 1. row ***************************
       Database: db1
Create Database: CREATE DATABASE `db1` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ /*!80016 DEFAULT ENCRYPTION='N' */
1 row in set (0.00 sec)

5、创建数据库

bash 复制代码
 创建数据库
mysql> create database db1;
Query OK, 1 row affected (0.01 sec)

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

6、删除数据库

bash 复制代码
 删除数据库
mysql> drop database db1;
Query OK, 0 rows affected (0.03 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

7、数据类型

整数数据类型

类型 字节 有符号范围 无符号 (UNSIGNED) 范围
TINYINT 1 字节 -128 ~ 127 0 ~ 255
SMALLINT 2 字节 -32768 ~ 32767 0 ~ 65535
MEDIUMINT 3 字节 -8388608 ~ 8388607 0 ~ 16777215
INT / INTEGER 4 字节 -2147483648 ~ 2147483647 0 ~ 4294967295
BIGINT 8 字节 -9223372036854775808 ~ 9223372036854775807 0 ~ 18446744073709551615

浮点数 & 定点数数据类型

类型 说明
FLOAT 单精度浮点数,4 字节,存在精度丢失
DOUBLE 双精度浮点数,8 字节,存在精度丢失
DECIMAL(M,D) 定点数,高精度,适合金额 M:总位数;D:小数位数 例:DECIMAL(5,2) →最大 999.99

字符串数据类型

类型 特点 最大长度 适用场景
CHAR(N) 定长,空间固定,查询快 最多 255 字符 短且固定长度:手机号、IP
VARCHAR(N) 变长,占用实际字符空间 MySQL8.0 最大 65535 字节 姓名、地址,最常用
TEXT 大文本,无默认值,不能有索引 65535 字节 文章、备注长文本
LONGTEXT 超大文本 4GB 超长内容

时间数据类型

类型 格式 示例
DATE 日期,年月日 2026‑08‑25
TIME 时间,时分秒 14:30:00
DATETIME 日期 + 时间 2026‑08‑25 14:30:00
TIMESTAMP 时间戳,1970‑01‑01 起秒数,会自动时区转换 同上
YEAR 年份 2026

修饰符

修饰符 全称 作用 适用类型 注意事项
UNSIGNED 无符号 取消负数,只能存 0 和正数 所有整数类型(tinyint/int/bigint...) tinyint unsigned:0‑255
NOT NULL 非空约束 字段禁止存入 NULL,插入必须赋值 全部数据类型 不加时默认允许 NULL
DEFAULT 值 默认值 不给该字段赋值时,自动填入预设数值 全部数据类型 有默认值≠NOT NULL,可手动插入 NULL
AUTO_INCREMENT 自增 自动生成递增数字 仅整数类型 必须加在主键 / 唯一索引上,一张表最多 1 个自增列
PRIMARY KEY 主键 唯一 + 非空,标识一行记录 任意类型 一张表只能有 1 个主键;可多字段组成联合主键
UNIQUE 唯一约束 字段的值不能重复 任意类型 允许存 NULL,并且可以有多条 NULL;一张表可多个唯一约束
COMMENT '说明' 注释 给字段添加文字备注,不影响数据 任意类型 仅说明,不对数据做限制

8、查看表

bash 复制代码
mysql> show tables;
+------------------------------------------------------+
| Tables_in_mysql                                      |
+------------------------------------------------------+
| columns_priv                                         |
| component                                            |
| db                                                   |
.........................
| time_zone_transition_type                            |
| user                                                 |
+------------------------------------------------------+
38 rows in set (0.01 sec)

mysql> show tables from mysql;
+------------------------------------------------------+
| Tables_in_mysql                                      |
+------------------------------------------------------+
| columns_priv                                         |
| component                                            |
| db                                                   |
...........................................
| time_zone_transition_type                            |
| user                                                 |
+------------------------------------------------------+
38 rows in set (0.00 sec)

mysql> show create table user;
+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
+-------+-----------------------------------------------------------------------------------------------------------------------------------+
| user  | CREATE TABLE `user` (
  `Host` char(255) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL DEFAULT '',
  `User` char(32) COLLATE utf8mb3_bin NOT NULL DEFAULT '',
  `Select_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Insert_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Update_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Delete_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Create_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Drop_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Reload_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Shutdown_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Process_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `File_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Grant_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `References_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Index_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Alter_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Show_db_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Super_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Create_tmp_table_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Lock_tables_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Execute_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Repl_slave_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Repl_client_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Create_view_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Show_view_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Create_routine_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Alter_routine_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Create_user_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Event_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Trigger_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Create_tablespace_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `ssl_type` enum('','ANY','X509','SPECIFIED') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '',
  `ssl_cipher` blob NOT NULL,
  `x509_issuer` blob NOT NULL,
  `x509_subject` blob NOT NULL,
  `max_questions` int unsigned NOT NULL DEFAULT '0',
  `max_updates` int unsigned NOT NULL DEFAULT '0',
  `max_connections` int unsigned NOT NULL DEFAULT '0',
  `max_user_connections` int unsigned NOT NULL DEFAULT '0',
  `plugin` char(64) COLLATE utf8mb3_bin NOT NULL DEFAULT 'caching_sha2_password',
  `authentication_string` text COLLATE utf8mb3_bin,
  `password_expired` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `password_last_changed` timestamp NULL DEFAULT NULL,
  `password_lifetime` smallint unsigned DEFAULT NULL,
  `account_locked` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Create_role_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Drop_role_priv` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'N',
  `Password_reuse_history` smallint unsigned DEFAULT NULL,
  `Password_reuse_time` smallint unsigned DEFAULT NULL,
  `Password_require_current` enum('N','Y') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
  `User_attributes` json DEFAULT NULL,
  PRIMARY KEY (`Host`,`User`)
) /*!50100 TABLESPACE `mysql` */ ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_bin STATS_PERSISTENT=0 ROW_FORMAT=DYNAMIC COMMENT='Users and global privileges' |
+-------+----------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)



mysql> show columns from user;
+--------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Field                    | Type                              | Null | Key | Default               | Extra |
+--------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Host                     | char(255)                         | NO   .....
| User_attributes          | json                              | YES  |     | NULL                  |       |
+--------------------------+-----------------------------------+------+-----+-----------------------+-------+
51 rows in set (0.01 sec)


mysql> show full columns from user;
+--------------------------+-----------------------------------+--------------------+------+-----+-----------------------+-------+---------------------------------+---------+
| Field                    | Type                              | Collation          | Null | Key | Default               | Extra | Privileges                      | Comment |
+--------------------------+-----------------------------------+--------------------+------+-----+-----------------------+-------+---------------------------------+---------+
| Host                     | char(255)                         | ascii_general_ci   | NO   | PRI |                       |       | select,insert,update,references |         |
| User                     | char(32)                          | utf8mb3_bin        | NO   | PRI |                       |       | select,insert,update,references |         |
........
                | NULL               | YES  |     | NULL                  |       | select,insert,update,references |         |
+--------------------------+-----------------------------------+--------------------+------+-----+-----------------------+-------+---------------------------------+---------+
51 rows in set (0.00 sec)

9、创建表

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

mysql> use db1;
Database changed
mysql> \s
--------------
mysql  Ver 8.4.11 for Linux on x86_64 (MySQL Community Server - GPL)

Connection id:          10
Current database:       db1
Current user:           root@localhost
SSL:                    Not in use
Current pager:          stdout
Using outfile:          ''
Using delimiter:        ;
Server version:         8.4.11 MySQL Community Server - GPL
Protocol version:       10
Connection:             Localhost via UNIX socket
Server characterset:    utf8mb4
Db     characterset:    utf8mb4
Client characterset:    utf8mb4
Conn.  characterset:    utf8mb4
UNIX socket:            /var/run/mysqld/mysqld.sock
Binary data as:         Hexadecimal
Uptime:                 37 min 21 sec

Threads: 2  Questions: 73  Slow queries: 0  Opens: 228  Flush tables: 3  Open tables: 145  Queries per second avg: 0.032
--------------


mysql> create table test(
    -> id int,
    -> name varchar(10),
    -> age int
    -> );
Query OK, 0 rows affected (0.02 sec)

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.02 sec)

mysql> create table user1 select User,Host from mysql.user;
Query OK, 4 rows affected (0.03 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> create table user2 like user1;
Query OK, 0 rows affected (0.03 sec)

10、修改表

bash 复制代码
mysql> alter table student rename stu;
Query OK, 0 rows affected (0.02 sec)

mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| stu           |
| test          |
| user1         |
+---------------+
3 rows in set (0.00 sec)


mysql> alter table stu add phone varchar(11) after name;
Query OK, 0 rows affected (0.07 sec)
Records: 0  Duplicates: 0  Warnings: 0

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


mysql> alter table stu drop column gender;
Query OK, 0 rows affected (0.06 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc stu;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int unsigned     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(20)      | NO   |     | NULL    |                |
| phone | varchar(11)      | YES  |     | NULL    |                |
| age   | tinyint unsigned | YES  |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)


mysql> alter table stu modify phone int;
Query OK, 0 rows affected (0.07 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc stu;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int unsigned     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(20)      | NO   |     | NULL    |                |
| phone | int              | YES  |     | NULL    |                |
| age   | tinyint unsigned | YES  |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)


mysql> alter table stu change column phone mobile char(11);
Query OK, 0 rows affected (0.07 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc stu;
+--------+------------------+------+-----+---------+----------------+
| Field  | Type             | Null | Key | Default | Extra          |
+--------+------------------+------+-----+---------+----------------+
| id     | int unsigned     | NO   | PRI | NULL    | auto_increment |
| name   | varchar(20)      | NO   |     | NULL    |                |
| mobile | char(11)         | YES  |     | NULL    |                |
| age    | tinyint unsigned | YES  |     | NULL    |                |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)



mysql> alter table stu alter column age set default '18';
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc stu;
+--------+------------------+------+-----+---------+----------------+
| Field  | Type             | Null | Key | Default | Extra          |
+--------+------------------+------+-----+---------+----------------+
| id     | int unsigned     | NO   | PRI | NULL    | auto_increment |
| name   | varchar(20)      | NO   |     | NULL    |                |
| mobile | char(11)         | YES  |     | NULL    |                |
| age    | tinyint unsigned | YES  |     | 18      |                |
+--------+------------------+------+-----+---------+----------------+



mysql> alter table stu add is_del bool default false;
Query OK, 0 rows affected (0.06 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc stu;
+--------+------------------+------+-----+---------+----------------+
| Field  | Type             | Null | Key | Default | Extra          |
+--------+------------------+------+-----+---------+----------------+
| id     | int unsigned     | NO   | PRI | NULL    | auto_increment |
| name   | varchar(20)      | NO   |     | NULL    |                |
| mobile | char(11)         | YES  |     | NULL    |                |
| age    | tinyint unsigned | YES  |     | 18      |                |
| is_del | tinyint(1)       | YES  |     | 0       |                |
+--------+------------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)

11、删除表

bash 复制代码
mysql> drop table user2;
Query OK, 0 rows affected (0.02 sec)


mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| stu           |
| student2      |
| test          |
| user1         |
+---------------+
4 rows in set (0.01 sec)

mysql> drop table user1;drop table test;
Query OK, 0 rows affected (0.02 sec)

Query OK, 0 rows affected (0.01 sec)

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

12、主键操作

bash 复制代码
mysql> create table student2 select name,age from stu;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc student2
    -> ;
+-------+------------------+------+-----+---------+-------+
| Field | Type             | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| name  | varchar(20)      | NO   |     | NULL    |       |
| age   | tinyint unsigned | YES  |     | 18      |       |
+-------+------------------+------+-----+---------+-------+
2 rows in set (0.01 sec)



mysql> alter table student2 add primary key (name);
Query OK, 0 rows affected (0.06 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc student2;
+-------+------------------+------+-----+---------+-------+
| Field | Type             | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| name  | varchar(20)      | NO   | PRI | NULL    |       |
| age   | tinyint unsigned | YES  |     | 18      |       |
+-------+------------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

mysql> alter table student2 drop primary key;
Query OK, 0 rows affected (0.06 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc student2;
+-------+------------------+------+-----+---------+-------+
| Field | Type             | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| name  | varchar(20)      | NO   |     | NULL    |       |
| age   | tinyint unsigned | YES  |     | 18      |       |
+-------+------------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> alter table student2 add id int unsigned first;
Query OK, 0 rows affected (0.06 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc student2;
+-------+------------------+------+-----+---------+-------+
| Field | Type             | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| id    | int unsigned     | YES  |     | NULL    |       |
| name  | varchar(20)      | NO   |     | NULL    |       |
| age   | tinyint unsigned | YES  |     | 18      |       |
+-------+------------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> ALTER TABLE student2 MODIFY COLUMN id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY;
Query OK, 0 rows affected (0.08 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc student2;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int unsigned     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(20)      | NO   |     | NULL    |                |
| age   | tinyint unsigned | YES  |     | 18      |                |
+-------+------------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)

mysql> alter table student2 drop id;
Query OK, 0 rows affected (0.06 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc student2;
+-------+------------------+------+-----+---------+-------+
| Field | Type             | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| name  | varchar(20)      | NO   |     | NULL    |       |
| age   | tinyint unsigned | YES  |     | 18      |       |
+-------+------------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

mysql>  ALTER TABLE student2 ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY FIRST;
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc student2;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int              | NO   | PRI | NULL    | auto_increment |
| name  | varchar(20)      | NO   |     | NULL    |                |
| age   | tinyint unsigned | YES  |     | 18      |                |
+-------+------------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)

13、插入数据

bash 复制代码
mysql> INSERT stu (name,age) VALUES('xyx',18);
Query OK, 1 row affected (0.02 sec)

mysql> select * from stu;
+----+------+--------+------+--------+
| id | name | mobile | age  | is_del |
+----+------+--------+------+--------+
| 10 | xyx  | NULL   |   18 |      1 |
+----+------+--------+------+--------+
1 row in set (0.00 sec)

mysql> INSERT stu (name,age) select name,age from stu;
Query OK, 2 rows affected (0.02 sec)
Records: 2  Duplicates: 0  Warnings: 0


mysql> INSERT INTO stu VALUES(30,'myy',12345678910,17,false);
Query OK, 1 row affected (0.01 sec)

mysql> select * from stu;
+----+------+-------------+------+--------+
| id | name | mobile      | age  | is_del |
+----+------+-------------+------+--------+
| 10 | xyx  | NULL        |   18 |      1 |
| 11 | xyy  | NULL        |   19 |      1 |
| 12 | xyx  | NULL        |   18 |      1 |
| 13 | xyy  | NULL        |   19 |      1 |
| 15 | xyx  | NULL        |   18 |      1 |
| 16 | xyy  | NULL        |   19 |      1 |
| 17 | xyx  | NULL        |   18 |      1 |
| 18 | xyy  | NULL        |   19 |      1 |
| 22 | xyx  | NULL        |   18 |      1 |
| 23 | xyy  | NULL        |   19 |      1 |
| 24 | xyx  | NULL        |   18 |      1 |
| 25 | xyy  | NULL        |   19 |      1 |
| 26 | xyx  | NULL        |   18 |      1 |
| 27 | xyy  | NULL        |   19 |      1 |
| 28 | xyx  | NULL        |   18 |      1 |
| 29 | xyy  | NULL        |   19 |      1 |
| 30 | myy  | 12345678910 |   17 |      0 |
+----+------+-------------+------+--------+
17 rows in set (0.00 sec)

mysql> INSERT INTO stu (name,mobile,age) VALUES('nyy',23456789101,19),('fyy',12345678910,22);
Query OK, 2 rows affected (0.02 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from stu where id>30;
+----+------+-------------+------+--------+
| id | name | mobile      | age  | is_del |
+----+------+-------------+------+--------+
| 37 | nyy  | 23456789101 |   19 |      1 |
| 38 | fyy  | 12345678910 |   22 |      1 |
+----+------+-------------+------+--------+

14、更新数据

bash 复制代码
#全表更新禁用
mysql> UPDATE stu SET age=18;
Query OK, 11 rows affected (0.01 sec)
Rows matched: 19  Changed: 11  Warnings: 0

mysql> select * from stu;
+----+------+-------------+------+--------+
| id | name | mobile      | age  | is_del |
+----+------+-------------+------+--------+
| 10 | xyx  | NULL        |   18 |      1 |
| 11 | xyy  | NULL        |   18 |      1 |
| 12 | xyx  | NULL        |   18 |      1 |
| 13 | xyy  | NULL        |   18 |      1 |
| 15 | xyx  | NULL        |   18 |      1 |
| 16 | xyy  | NULL        |   18 |      1 |
| 17 | xyx  | NULL        |   18 |      1 |
| 18 | xyy  | NULL        |   18 |      1 |
| 22 | xyx  | NULL        |   18 |      1 |
| 23 | xyy  | NULL        |   18 |      1 |
| 24 | xyx  | NULL        |   18 |      1 |
| 25 | xyy  | NULL        |   18 |      1 |
| 26 | xyx  | NULL        |   18 |      1 |
| 27 | xyy  | NULL        |   18 |      1 |
| 28 | xyx  | NULL        |   18 |      1 |
| 29 | xyy  | NULL        |   18 |      1 |
| 30 | myy  | 12345678910 |   18 |      0 |
| 37 | nyy  | 23456789101 |   18 |      1 |
| 38 | fyy  | 12345678910 |   18 |      1 |
+----+------+-------------+------+--------+
19 rows in set (0.00 sec)


mysql> update stu set name='myy' where name='fyy';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from stu where name='myy';
+----+------+-------------+------+--------+
| id | name | mobile      | age  | is_del |
+----+------+-------------+------+--------+
| 30 | myy  | 12345678910 |   18 |      0 |
| 38 | myy  | 12345678910 |   18 |      1 |
+----+------+-------------+------+--------+
2 rows in set (0.00 sec)

15、删除数据

bash 复制代码
mysql> delete from stu where id=12;
Query OK, 1 row affected (0.01 sec)

mysql> select * from stu;
+----+------+-------------+------+--------+
| id | name | mobile      | age  | is_del |
+----+------+-------------+------+--------+
| 10 | xyx  | NULL        |   18 |      1 |
| 11 | xyy  | NULL        |   18 |      1 |
| 13 | xyy  | NULL        |   18 |      1 |
| 15 | xyx  | NULL        |   18 |      1 |
| 16 | xyy  | NULL        |   18 |      1 |
| 17 | xyx  | NULL        |   18 |      1 |
| 18 | xyy  | NULL        |   18 |      1 |
| 22 | xyx  | NULL        |   18 |      1 |
| 23 | xyy  | NULL        |   18 |      1 |
| 24 | xyx  | NULL        |   18 |      1 |
| 25 | xyy  | NULL        |   18 |      1 |
| 26 | xyx  | NULL        |   18 |      1 |
| 27 | xyy  | NULL        |   18 |      1 |
| 28 | xyx  | NULL        |   18 |      1 |
| 29 | xyy  | NULL        |   18 |      1 |
| 30 | myy  | 12345678910 |   18 |      0 |
| 37 | nyy  | 23456789101 |   18 |      1 |
| 38 | myy  | 12345678910 |   18 |      1 |
+----+------+-------------+------+--------+
18 rows in set (0.00 sec)

mysql> delete from stu where ( modile IS NULL and id=25);
ERROR 1054 (42S22): Unknown column 'modile' in 'where clause'
mysql> delete from stu;
Query OK, 18 rows affected (0.01 sec)

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

mysql> truncate table student2;
Query OK, 0 rows affected (0.05 sec)

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

16、查询

bash 复制代码
mysql> select * from stu;
+----+-------+--------+------+--------+
| id | name  | mobile | age  | is_del |
+----+-------+--------+------+--------+
|  1 | test1 | NULL   |   20 |      1 |
|  2 | test2 | NULL   |   21 |      1 |
|  3 | test3 | NULL   |   22 |      1 |
+----+-------+--------+------+--------+
3 rows in set (0.01 sec)

mysql> select name as 姓名,age from stu;
+--------+------+
| 姓名   | age  |
+--------+------+
| test1  |   20 |
| test2  |   21 |
| test3  |   22 |
+--------+------+
3 rows in set (0.01 sec)

mysql> select * from stu;
+----+-------+--------+------+--------+
| id | name  | mobile | age  | is_del |
+----+-------+--------+------+--------+
|  1 | test1 | NULL   |   20 |      1 |
|  2 | test2 | NULL   |   21 |      1 |
|  3 | test3 | NULL   |   22 |      1 |
+----+-------+--------+------+--------+
3 rows in set (0.01 sec)

mysql> select name as 姓名,age from stu;
+--------+------+
| 姓名   | age  |
+--------+------+
| test1  |   20 |
| test2  |   21 |
| test3  |   22 |
+--------+------+
3 rows in set (0.01 sec)

mysql> select * from stu;
+----+----------+-------------+------+--------+
| id | name     | mobile      | age  | is_del |
+----+----------+-------------+------+--------+
|  1 | test1    | NULL        |   20 |      1 |
|  2 | test2    | NULL        |   21 |      1 |
|  3 | test3    | NULL        |   22 |      1 |
|  4 | user1    | 13812345678 |   18 |      1 |
|  5 | user2    | 11212345678 |   18 |      1 |
|  6 | user3    | NULL        |   18 |      1 |
|  7 | zhangsan | NULL        |   18 |      1 |
|  8 | lisi     | NULL        |   18 |      1 |
|  9 | wangwu   | NULL        |   18 |      1 |
+----+----------+-------------+------+--------+
9 rows in set (0.00 sec)

mysql> select id,name from stu where id=2;
+----+-------+
| id | name  |
+----+-------+
|  2 | test2 |
+----+-------+
1 row in set (0.00 sec)

mysql> select id,name from stu where id in (2,4,6);
+----+-------+
| id | name  |
+----+-------+
|  2 | test2 |
|  4 | user1 |
|  6 | user3 |
+----+-------+
3 rows in set (0.00 sec)

mysql> select id,name from stu where id>=2 and id<4
    -> ;
+----+-------+
| id | name  |
+----+-------+
|  2 | test2 |
|  3 | test3 |
+----+-------+
2 rows in set (0.01 sec)

mysql> select id,name from stu where id>=2 or id<4;
+----+----------+
| id | name     |
+----+----------+
|  1 | test1    |
|  2 | test2    |
|  3 | test3    |
|  4 | user1    |
|  5 | user2    |
|  6 | user3    |
|  7 | zhangsan |
|  8 | lisi     |
|  9 | wangwu   |
+----+----------+
9 rows in set (0.00 sec)

mysql> select id, name from stu where name like 'te%';
+----+-------+
| id | name  |
+----+-------+
|  1 | test1 |
|  2 | test2 |
|  3 | test3 |
+----+-------+
3 rows in set (0.01 sec)

mysql> select id, name from stu where name like '%e%';
+----+-------+
| id | name  |
+----+-------+
|  1 | test1 |
|  2 | test2 |
|  3 | test3 |
|  4 | user1 |
|  5 | user2 |
|  6 | user3 |
+----+-------+
6 rows in set (0.00 sec)

mysql> select id, name from stu where name like '1$';
Empty set (0.00 sec)

mysql> select id,name from stu where name like 'zh%' or name like 't%';
+----+----------+
| id | name     |
+----+----------+
|  1 | test1    |
|  2 | test2    |
|  3 | test3    |
|  7 | zhangsan |
+----+----------+
4 rows in set (0.00 sec)

mysql> select id,name from stu where id between 6 and 8;
+----+----------+
| id | name     |
+----+----------+
|  6 | user3    |
|  7 | zhangsan |
|  8 | lisi     |
+----+----------+
3 rows in set (0.01 sec)


mysql> select id,name from stu where id not between 6 and 8;
+----+--------+
| id | name   |
+----+--------+
|  1 | test1  |
|  2 | test2  |
|  3 | test3  |
|  4 | user1  |
|  5 | user2  |
|  9 | wangwu |
+----+--------+
6 rows in set (0.01 sec)

mysql> select id,name from stu where id in (2,4,6);
+----+-------+
| id | name  |
+----+-------+
|  2 | test2 |
|  4 | user1 |
|  6 | user3 |
+----+-------+
3 rows in set (0.00 sec)

mysql> select id,name from stu where id not in (2,4,6);
+----+----------+
| id | name     |
+----+----------+
|  1 | test1    |
|  3 | test3    |
|  5 | user2    |
|  7 | zhangsan |
|  8 | lisi     |
|  9 | wangwu   |
+----+----------+
6 rows in set (0.00 sec)

mysql> select count(*) as total from stu;
+-------+
| total |
+-------+
|     9 |
+-------+
1 row in set (0.03 sec)

mysql> select count(mobile) as total from stu;
+-------+
| total |
+-------+
|     2 |
+-------+
1 row in set (0.01 sec)

mysql> select max(id),min(id),avg(age) from stu;
+---------+---------+----------+
| max(id) | min(id) | avg(age) |
+---------+---------+----------+
|       9 |       1 |  19.0000 |
+---------+---------+----------+
1 row in set (0.01 sec)

mysql>

Linux学习之旅之MySQL用户管理

一、用户基础知识

bash 复制代码
完整用户名格式:'用户名'@'主机地址'

MySQL 用户不是单靠名字,用户名 + 主机 组合才是唯一账号
主机 说明
'root'@'localhost' 只能本机登录,127.0.0.1,不允许外网
'user1'@'192.168.1.100' 只能从这个 IP 登录
'user1'@'192.168.1.%' 192.168.1 网段所有机器,% 通配符
'user1'@'%' 任意 IP 都可以远程登录
bash 复制代码
mysql> select Host,User from mysql.user;
+-----------+------------------+
| Host      | User             |
+-----------+------------------+
| localhost | mysql.infoschema |
| localhost | mysql.session    |
| localhost | mysql.sys        |
| localhost | root             |
+-----------+------------------+
4 rows in set (0.01 sec)


mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

二、用户管理

1、创建用户

bash 复制代码
mysql> create user 'xyx'@'10.0.0.%' identified by 'Xyx@123456';
Query OK, 0 rows affected (0.11 sec)

mysql> select host,user from mysql.user;
+-----------+------------------+
| host      | user             |
+-----------+------------------+
| 10.0.0.%  | xyx              |
| localhost | mysql.infoschema |
| localhost | mysql.session    |
| localhost | mysql.sys        |
| localhost | root             |
+-----------+------------------+
5 rows in set (0.01 sec)

2、修改用户

bash 复制代码
mysql> rename user 'xyx'@'10.0.0.%' to 'xyx'@'%';
Query OK, 0 rows affected (0.02 sec)

mysql> select host,user from mysql.user;
+-----------+------------------+
| host      | user             |
+-----------+------------------+
| %         | xyx              |
| localhost | mysql.infoschema |
| localhost | mysql.session    |
| localhost | mysql.sys        |
| localhost | root             |
+-----------+------------------+
5 rows in set (0.01 sec)

3、删除用户

bash 复制代码
mysql> drop user 'xyx'@'%';
Query OK, 0 rows affected (0.01 sec)

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

4、修改密码

bash 复制代码
mysql> create user 'xyx'@'10.0.0.%' identified by 'Xyx@123456';
Query OK, 0 rows affected (0.02 sec)

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

mysql> alter user 'xyx'@'10.0.0.%' identified by 'Xyx@1234';
Query OK, 0 rows affected (0.02 sec)

三、权限管理

1、权限对比

bash 复制代码
#root用户
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| db1                |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.02 sec)

#未授权普通用户xyx
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| performance_schema |
+--------------------+
2 rows in set (0.02 sec)


mysql> create database db2;
ERROR 1044 (42000): Access denied for user 'xyx'@'10.0.0.%' to database 'db2'
mysql>

2、授权

bash 复制代码
#grant 权限列表 on 库.表 to '用户名'@'主机';
mysql> grant all on *.* to 'xyx'@'10.0.0.%';
Query OK, 0 rows affected (0.02 sec)

#授权后
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| db1                |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.01 sec)


#此时用户xyx没有授权权限
mysql> create user 'myy'@'%' identified by 'Myy@1234';
Query OK, 0 rows affected (0.02 sec)

mysql> grant all on *.* to 'myy'@'%';
ERROR 1045 (28000): Access denied for user 'xyx'@'10.0.0.%' (using password: YES)

#权限授权后

mysql> grant all on *.* to 'xyx'@'10.0.0.%' with grant option;
Query OK, 0 rows affected (0.02 sec)

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

mysql> grant all on *.* to 'myy'@'%';
Query OK, 0 rows affected (0.03 sec)


#取消授权
mysql> revoke all on *.* from 'myy'@'%';
Query OK, 0 rows affected (0.01 sec)

四、索引

1、索引是什么

bash 复制代码
#索引就是数据库给表建立的「目录」,作用是加快查询速度,代价是占用磁盘空间、减慢增删改 (INSERT/UPDATE/DELETE) 速度。

#InnoDB是最常用存储引擎,索引底层是 B+ Tree
特点:
--所有数据都存在叶子节点
--叶子节点用链表相连,范围查询非常快
--非叶子节点只存索引键,不存真实数据,树高度很低,查询磁盘 IO 少

2、创建与删除索引

bash 复制代码
mysql> create index username on stu(name);
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc stu;
+--------+------------------+------+-----+---------+----------------+
| Field  | Type             | Null | Key | Default | Extra          |
+--------+------------------+------+-----+---------+----------------+
| id     | int unsigned     | NO   | PRI | NULL    | auto_increment |
| name   | char(30)         | YES  | MUL | NULL    |                |
| mobile | char(11)         | YES  |     | NULL    |                |
| age    | tinyint unsigned | YES  |     | 18      |                |
| is_del | tinyint(1)       | YES  |     | 1       |                |
+--------+------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)


mysql> show index from stu\G
*************************** 2. row ***************************
        Table: stu
   Non_unique: 1
     Key_name: username
 Seq_in_index: 1
  Column_name: name
    Collation: A
  Cardinality: 9
     Sub_part: NULL
       Packed: NULL
         Null: YES
   Index_type: BTREE
      Comment:
Index_comment:
      Visible: YES
   Expression: NULL
2 rows in set (0.00 sec)

mysql> drop index username on stu;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> show index from stu\G
*************************** 1. row ***************************
        Table: stu
   Non_unique: 0
     Key_name: PRIMARY
 Seq_in_index: 1
  Column_name: id
    Collation: A
  Cardinality: 9
     Sub_part: NULL
       Packed: NULL
         Null:
   Index_type: BTREE
      Comment:
Index_comment:
      Visible: YES
   Expression: NULL
1 row in set (0.00 sec)

mysql> desc stu;
+--------+------------------+------+-----+---------+----------------+
| Field  | Type             | Null | Key | Default | Extra          |
+--------+------------------+------+-----+---------+----------------+
| id     | int unsigned     | NO   | PRI | NULL    | auto_increment |
| name   | char(30)         | YES  |     | NULL    |                |
| mobile | char(11)         | YES  |     | NULL    |                |
| age    | tinyint unsigned | YES  |     | 18      |                |
| is_del | tinyint(1)       | YES  |     | 1       |                |
+--------+------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

五、环境变量和属性

1、变量种类

变量类型 符号 / 关键字 作用范围 生命周期 修改后是否永久
全局变量 @@global.变量名 所有新的客户端连接 MySQL 服务运行期间,重启失效 ❌临时 set 修改会丢失;写到 my.cnf 才永久
会话变量 @@session.变量名 / @@local.变量名 仅当前这一个数据库连接 断开连接立刻消失 ❌断开就失效
用户自定义变量 @变量名 当前会话连接 断开连接立刻消失 ❌断开就失效

2、查看变量

bash 复制代码
mysql> show variables like "log%";
+----------------------------------------+----------------------------------------+
| Variable_name                          | Value                                  |
+----------------------------------------+----------------------------------------+
| log_bin                                | ON                                     |
| log_bin_basename                       | /var/lib/mysql/binlog                  |
| log_bin_index                          | /var/lib/mysql/binlog.index            |
| log_bin_trust_function_creators        | OFF                                    |
| log_error                              | /var/log/mysql/error.log               |
| log_error_services                     | log_filter_internal; log_sink_internal |
| log_error_suppression_list             |                                        |
| log_error_verbosity                    | 2                                      |
| log_timestamps                         | UTC                                    |
+----------------------------------------+----------------------------------------+
20 rows in set (0.00 sec)

mysql> SELECT @@global.max_connections;
+--------------------------+
| @@global.max_connections |
+--------------------------+
|                      151 |
+--------------------------+
1 row in set (0.00 sec)

3、修改全局变量

bash 复制代码
mysql> set global max_connections=2000;
Query OK, 0 rows affected (0.00 sec)

mysql> select @@global.max_connections;
+--------------------------+
| @@global.max_connections |
+--------------------------+
|                     2000 |
+--------------------------+
1 row in set (0.00 sec)

4、修改会话变量

bash 复制代码
mysql> select @@session.autocommit;
+----------------------+
| @@session.autocommit |
+----------------------+
|                    1 |
+----------------------+
1 row in set (0.00 sec)

mysql> select @@session.autocommit;
+----------------------+
| @@session.autocommit |
+----------------------+
|                    0 |
+----------------------+
1 row in set (0.00 sec)

5、自定义变量

bash 复制代码
mysql> select @@session.autocommit;
+----------------------+
| @@session.autocommit |
+----------------------+
|                    0 |
+----------------------+
1 row in set (0.00 sec)

mysql> set @xyx='XYX';
Query OK, 0 rows affected (0.00 sec)

mysql> select @xyx;
+------+
| @xyx |
+------+
| XYX  |
+------+
1 row in set (0.00 sec)


root@MySQL-13:/etc/mysql# pwd
/etc/mysql
root@MySQL-13:/etc/mysql# ls
conf.d  my.cnf mysql.conf.d

Linux学习之旅之MySQL日志

一、事务

1、什么是事务

bash 复制代码
---事务是一组具有原子性的 SQL 语句,或者说一个独立单元。可以理解为一个事务对应的是一组完整的业务,这个业务有一条或多条 SQL 语句组成。所谓原子性是指,这一组业务中的 SQL 语句不可分割,所以,要么全部SQL 语句都执行成功,事务也就执行成功;只要有一条 SQL 语句执行失败,则整个事务都要回滚到事务开始前。

2、事务日志

bash 复制代码
--记录事务的日志,可以根据此日志实现事务的回滚(undo),重新提交(redo) 等功能

3、事务特性

特性 英文 中文 核心含义 底层保障 (InnoDB)
A Atomicity 原子性 事务内操作要么全部成功,要么全部失败回滚 undo log 回滚日志
C Consistency 一致性 事务前后数据完整性不变,业务规则合法 原子 + 隔离 + 持久性共同保障
I Isolation 隔离性 并发多个事务,彼此之间相互隔离互不干扰 锁 + MVCC
D Durability 持久性 事务 commit 提交成功,修改永久生效,宕机不丢失 redo log 重做日志

4、流程

plaintext 复制代码
开启事务BEGIN
    ↓
执行增删改
    ↓
├─commit → 提交,数据生效✅
└─rollback → 回滚,撤销修改❌

5、实操事务

bash 复制代码
#终端1开启前查询
mysql> select * from stu;
+----+----------+-------------+------+--------+
| id | name     | mobile      | age  | is_del |
+----+----------+-------------+------+--------+
|  1 | test1    | NULL        |   20 |      1 |
|  2 | test2    | NULL        |   21 |      1 |
|  3 | test3    | NULL        |   22 |      1 |
|  4 | user1    | 13812345678 |   18 |      1 |
|  5 | user2    | 11212345678 |   18 |      1 |
|  6 | user3    | NULL        |   18 |      1 |
|  7 | zhangsan | NULL        |   18 |      1 |
|  8 | lisi     | NULL        |   18 |      1 |
|  9 | wangwu   | NULL        |   19 |      1 |
+----+----------+-------------+------+--------+
9 rows in set (0.00 sec)

#开始事务
mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> update stu set age=23 where id=9;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> insert into stu (name,mobile,age) values('zhangsan',1534489213,'44');
Query OK, 1 row affected (0.00 sec)

#未提交前
mysql> select * from stu;
+----+----------+-------------+------+--------+
| id | name     | mobile      | age  | is_del |
+----+----------+-------------+------+--------+
|  1 | test1    | NULL        |   20 |      1 |
|  2 | test2    | NULL        |   21 |      1 |
|  3 | test3    | NULL        |   22 |      1 |
|  4 | user1    | 13812345678 |   18 |      1 |
|  5 | user2    | 11212345678 |   18 |      1 |
|  6 | user3    | NULL        |   18 |      1 |
|  7 | zhangsan | NULL        |   18 |      1 |
|  8 | lisi     | NULL        |   18 |      1 |
|  9 | wangwu   | NULL        |   23 |      1 |
| 10 | zhangsan | 1534489213  |   44 |      1 |
+----+----------+-------------+------+--------+
10 rows in set (0.00 sec)

#终端2开启前查询
mysql> select * from stu;
+----+----------+-------------+------+--------+
| id | name     | mobile      | age  | is_del |
+----+----------+-------------+------+--------+
|  1 | test1    | NULL        |   20 |      1 |
|  2 | test2    | NULL        |   21 |      1 |
|  3 | test3    | NULL        |   22 |      1 |
|  4 | user1    | 13812345678 |   18 |      1 |
|  5 | user2    | 11212345678 |   18 |      1 |
|  6 | user3    | NULL        |   18 |      1 |
|  7 | zhangsan | NULL        |   18 |      1 |
|  8 | lisi     | NULL        |   18 |      1 |
|  9 | wangwu   | NULL        |   19 |      1 |
+----+----------+-------------+------+--------+
9 rows in set (0.00 sec)

#未提交查询
mysql> select * from stu;
+----+----------+-------------+------+--------+
| id | name     | mobile      | age  | is_del |
+----+----------+-------------+------+--------+
|  1 | test1    | NULL        |   20 |      1 |
|  2 | test2    | NULL        |   21 |      1 |
|  3 | test3    | NULL        |   22 |      1 |
|  4 | user1    | 13812345678 |   18 |      1 |
|  5 | user2    | 11212345678 |   18 |      1 |
|  6 | user3    | NULL        |   18 |      1 |
|  7 | zhangsan | NULL        |   18 |      1 |
|  8 | lisi     | NULL        |   18 |      1 |
|  9 | wangwu   | NULL        |   19 |      1 |
+----+----------+-------------+------+--------+
9 rows in set (0.00 sec)

-----------------------

#提交后
mysql> commit;
Query OK, 0 rows affected (0.01 sec)

mysql> select * from stu;
+----+----------+-------------+------+--------+
| id | name     | mobile      | age  | is_del |
+----+----------+-------------+------+--------+
|  1 | test1    | NULL        |   20 |      1 |
|  2 | test2    | NULL        |   21 |      1 |
|  3 | test3    | NULL        |   22 |      1 |
|  4 | user1    | 13812345678 |   18 |      1 |
|  5 | user2    | 11212345678 |   18 |      1 |
|  6 | user3    | NULL        |   18 |      1 |
|  7 | zhangsan | NULL        |   18 |      1 |
|  8 | lisi     | NULL        |   18 |      1 |
|  9 | wangwu   | NULL        |   23 |      1 |
| 10 | zhangsan | 1534489213  |   44 |      1 |
+----+----------+-------------+------+--------+
10 rows in set (0.00 sec)


#提交后
mysql> select * from stu;
+----+----------+-------------+------+--------+
| id | name     | mobile      | age  | is_del |
+----+----------+-------------+------+--------+
|  1 | test1    | NULL        |   20 |      1 |
|  2 | test2    | NULL        |   21 |      1 |
|  3 | test3    | NULL        |   22 |      1 |
|  4 | user1    | 13812345678 |   18 |      1 |
|  5 | user2    | 11212345678 |   18 |      1 |
|  6 | user3    | NULL        |   18 |      1 |
|  7 | zhangsan | NULL        |   18 |      1 |
|  8 | lisi     | NULL        |   18 |      1 |
|  9 | wangwu   | NULL        |   23 |      1 |
| 10 | zhangsan | 1534489213  |   44 |      1 |
+----+----------+-------------+------+--------+
10 rows in set (0.00 sec)



#测试

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

mysql> insert into stu (name,mobile,age) values ('lisi',12345612345,'33');
Query OK, 1 row affected (0.00 sec)

mysql> select * from stu;
+----+----------+-------------+------+--------+
| id | name     | mobile      | age  | is_del |
+----+----------+-------------+------+--------+
|  1 | test1    | NULL        |   20 |      1 |
|  2 | test2    | NULL        |   21 |      1 |
|  3 | test3    | NULL        |   22 |      1 |
|  4 | user1    | 13812345678 |   18 |      1 |
|  5 | user2    | 11212345678 |   18 |      1 |
|  6 | user3    | NULL        |   18 |      1 |
|  7 | zhangsan | NULL        |   18 |      1 |
|  8 | lisi     | NULL        |   18 |      1 |
|  9 | wangwu   | NULL        |   23 |      1 |
| 10 | zhangsan | 1534489213  |   44 |      1 |
| 11 | lisi     | 12345612345 |   33 |      1 |
+----+----------+-------------+------+--------+
11 rows in set (0.00 sec)

#回滚开始
mysql> rollback;
Query OK, 0 rows affected (0.01 sec)

mysql> select * from stu;
+----+----------+-------------+------+--------+
| id | name     | mobile      | age  | is_del |
+----+----------+-------------+------+--------+
|  1 | test1    | NULL        |   20 |      1 |
|  2 | test2    | NULL        |   21 |      1 |
|  3 | test3    | NULL        |   22 |      1 |
|  4 | user1    | 13812345678 |   18 |      1 |
|  5 | user2    | 11212345678 |   18 |      1 |
|  6 | user3    | NULL        |   18 |      1 |
|  7 | zhangsan | NULL        |   18 |      1 |
|  8 | lisi     | NULL        |   18 |      1 |
|  9 | wangwu   | NULL        |   23 |      1 |
| 10 | zhangsan | 1534489213  |   44 |      1 |
+----+----------+-------------+------+--------+
10 rows in set (0.00 sec)

6、增加保存点

plaintext 复制代码
开启事务
    ↓
执行SQL1
    ↓
设置保存点 savepoint sp1
    ↓
执行SQL2
    ↓
├─ commit          → 全部保存 ✅
├─ rollback to sp1 → 回到保存点,撤销SQL2,SQL1还在
└─ rollback        → 全部撤销 ❌

7、保存点实操

bash 复制代码
mysql> select * from stu2;
+----+----------+-------------+------+--------+
| id | name     | mobile      | age  | is_del |
+----+----------+-------------+------+--------+
|  1 | test1    | NULL        |   20 |      1 |
|  2 | test2    | NULL        |   21 |      1 |
|  3 | test3    | NULL        |   22 |      1 |
|  4 | user1    | 13812345678 |   18 |      1 |
|  5 | user2    | 11212345678 |   18 |      1 |
|  6 | user3    | NULL        |   18 |      1 |
|  7 | zhangsan | NULL        |   18 |      1 |
|  8 | lisi     | NULL        |   18 |      1 |
|  9 | wangwu   | NULL        |   23 |      1 |
| 10 | zhangsan | 1534489213  |   44 |      1 |
+----+----------+-------------+------+--------+
10 rows in set (0.00 sec)

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

mysql> insert into stu2 (name,age) values ('wanger','44');
Query OK, 1 row affected (0.00 sec)

mysql> savepoint d1;
Query OK, 0 rows affected (0.00 sec)

mysql> delete from stu2 where id=3;
Query OK, 1 row affected (0.00 sec)

mysql> savepoint d2;
Query OK, 0 rows affected (0.00 sec)

mysql> insert into stu2 (name,age) values ('mazi','43');
Query OK, 1 row affected (0.00 sec)

mysql> savepoint d3;
Query OK, 0 rows affected (0.01 sec)

mysql> select * from stu2;
+----+----------+-------------+------+--------+
| id | name     | mobile      | age  | is_del |
+----+----------+-------------+------+--------+
|  1 | test1    | NULL        |   20 |      1 |
|  2 | test2    | NULL        |   21 |      1 |
|  4 | user1    | 13812345678 |   18 |      1 |
|  5 | user2    | 11212345678 |   18 |      1 |
|  6 | user3    | NULL        |   18 |      1 |
|  7 | zhangsan | NULL        |   18 |      1 |
|  8 | lisi     | NULL        |   18 |      1 |
|  9 | wangwu   | NULL        |   23 |      1 |
| 10 | zhangsan | 1534489213  |   44 |      1 |
|  0 | wanger   | NULL        |   44 |      1 |
|  0 | mazi     | NULL        |   43 |      1 |
+----+----------+-------------+------+--------+
11 rows in set (0.00 sec)

#回滚到点1
mysql> rollback to d1;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from stu2;
+----+----------+-------------+------+--------+
| id | name     | mobile      | age  | is_del |
+----+----------+-------------+------+--------+
|  1 | test1    | NULL        |   20 |      1 |
|  2 | test2    | NULL        |   21 |      1 |
|  3 | test3    | NULL        |   22 |      1 |
|  4 | user1    | 13812345678 |   18 |      1 |
|  5 | user2    | 11212345678 |   18 |      1 |
|  6 | user3    | NULL        |   18 |      1 |
|  7 | zhangsan | NULL        |   18 |      1 |
|  8 | lisi     | NULL        |   18 |      1 |
|  9 | wangwu   | NULL        |   23 |      1 |
| 10 | zhangsan | 1534489213  |   44 |      1 |
|  0 | wanger   | NULL        |   44 |      1 |
+----+----------+-------------+------+--------+
11 rows in set (0.00 sec)

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

mysql> select * from stu2;
+----+----------+-------------+------+--------+
| id | name     | mobile      | age  | is_del |
+----+----------+-------------+------+--------+
|  1 | test1    | NULL        |   20 |      1 |
|  2 | test2    | NULL        |   21 |      1 |
|  3 | test3    | NULL        |   22 |      1 |
|  4 | user1    | 13812345678 |   18 |      1 |
|  5 | user2    | 11212345678 |   18 |      1 |
|  6 | user3    | NULL        |   18 |      1 |
|  7 | zhangsan | NULL        |   18 |      1 |
|  8 | lisi     | NULL        |   18 |      1 |
|  9 | wangwu   | NULL        |   23 |      1 |
| 10 | zhangsan | 1534489213  |   44 |      1 |
|  0 | wanger   | NULL        |   44 |      1 |
+----+----------+-------------+------+--------+
11 rows in set (0.00 sec)

8、事务异常

异常名称 说明
脏读 事务 A 读到事务 B还没有 commit 提交的数据。如果 B 回滚,A 读到的数据就是无效脏数据
不可重复读 同一个事务内,两次读取同一行。中间被别的事务 update+commit 修改,两次查询结果不一样。侧重【更新】
幻读 同一个事务,两次范围查询。别的事务执行了 insert/delete 并且提交,导致两次查询行数不一样。侧重【新增 / 删除】

9、事务异常隔离

隔离级别 脏读 不可重复读 幻读
READ‑UNCOMMITTED 读未提交 ✅允许 ✅允许 ✅允许
READ‑COMMITTED 读已提交 (RC) ❌解决 ✅允许 ✅允许
REPEATABLE‑READ 可重复读 (RR) MySQL 默认 ❌解决 ❌解决 ❌InnoDB 间隙锁解决幻读
SERIALIZABLE 串行化 ❌解决 ❌解决 ❌解决

10、查询事务隔离级别

bash 复制代码
#查询
mysql> select @@transaction_isolation;
+-------------------------+
| @@transaction_isolation |
+-------------------------+
| REPEATABLE-READ         |
+-------------------------+
1 row in set (0.00 sec)

mysql>

11、错误日志

取值 级别 记录内容 适用场景
1 Error 只记录 ERROR 错误 最小日志量,只看故障
2 Error+Warning 错误 + 警告信息(默认值 日常运维推荐
3 Error+Warning+Info 错误 + 警告 + 普通提示信息 排查启动、连接问题,最详细
bash 复制代码
#查询错误日志存放位置
mysql> show variables like "log%";
+----------------------------------------+----------------------------------------+
| log_error                              | /var/log/mysql/error.log               |

20 rows in set (0.04 sec)



#查看错误日志

root@MySQL-13:/etc/mysql# tail -f /var/log/mysql/error.log
2026-08-25T09:47:07.281928Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.4.11)  MySQL Community Server - GPL.
2026-08-25T09:47:07.282978Z 0 [System] [MY-015016] [Server] MySQL Server - end.
2026-08-26T00:18:30.304538Z 0 [System] [MY-015015] [Server] MySQL Server - start.
2026-08-26T00:18:34.365427Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.4.11) starting as process 1451
2026-08-26T00:18:34.528299Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2026-08-26T00:18:37.343399Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2026-08-26T00:18:38.444959Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2026-08-26T00:18:38.445051Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
2026-08-26T00:18:38.525426Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
2026-08-26T00:18:38.526105Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.4.11'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.

12、修改错误日志时区

bash 复制代码
root@MySQL-13:~# vim /etc/mysql/mysql.conf.d/mysqld.cnf
root@MySQL-13:~# tail -10 /etc/mysql/mysql.conf.d/mysqld.cnf

[mysqld]
log_timestamps  = SYSTEM

#修改配置文件必须重启
root@MySQL-13:~# systemctl restart mysql.service

root@MySQL-13:~# tail -f /var/log/mysql/error.log
2026-08-26T03:26:13.335274Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.4.11)  MySQL Community Server - GPL.
2026-08-26T03:26:13.335659Z 0 [System] [MY-015016] [Server] MySQL Server - end.
2026-08-26T03:26:14.131581-00:00 0 [System] [MY-015015] [Server] MySQL Server - start.
2026-08-26T03:26:15.423217-00:00 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.4.11) starting as process 2585

二、二进制日志

1、什么是二进制日志

bash 复制代码
---二进制日志(Binary Log)也可叫作变更日志(Update Log),是 MySQL 中非常重要的日志。主要用于记录数据库的变化情况,即 SQL 语句的 DDL 和 DML 语句,但不包含查询操作语句,因为查询语句并不
会改变数据库中的数据。
---如果 MySQL 数据库意外停止,可以通过二进制日志文件来查看用户执行了哪些操作,对数据库服务器文件做了哪些修改,然后根据二进制日志文件中的记录来恢复数据库服务器。

2、查看二进制日志状态

bash 复制代码
#查看是否开启
mysql> show variables like "log_bin%";
+---------------------------------+-----------------------------+
| Variable_name                   | Value                       |
+---------------------------------+-----------------------------+
| log_bin                         | ON                          |
| log_bin_basename                | /var/lib/mysql/binlog       |
| log_bin_index                   | /var/lib/mysql/binlog.index |
| log_bin_trust_function_creators | OFF                         |
+---------------------------------+-----------------------------+
4 rows in set (0.00 sec)

#查看有哪些二进制日志文件
mysql> show binary logs;
+---------------+-----------+-----------+
| Log_name      | File_size | Encrypted |
+---------------+-----------+-----------+
| binlog.000001 |       506 | No        |
| binlog.000002 |       181 | No        |
| binlog.000003 |       834 | No        |
| binlog.000004 |       530 | No        |
| binlog.000005 |       181 | No        |
| binlog.000006 |       181 | No        |
| binlog.000007 |      2149 | No        |
| binlog.000008 |       181 | No        |
| binlog.000009 |       181 | No        |
| binlog.000010 |     17156 | No        |
| binlog.000011 |      3818 | No        |
| binlog.000012 |       158 | No        |
+---------------+-----------+-----------+
12 rows in set (0.02 sec)

##查看当前在使用的日志文件
mysql> show binary log status;
+---------------+----------+--------------+------------------+-------------------+
| File          | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+---------------+----------+--------------+------------------+-------------------+
| binlog.000012 |      158 |              |                  |                   |
+---------------+----------+--------------+------------------+-------------------+
1 row in set (0.01 sec)

#查看全局日志和会话日志的开启状态
mysql> select @@log_bin,@@sql_log_bin;
+-----------+---------------+
| @@log_bin | @@sql_log_bin |
+-----------+---------------+
|         1 |             1 |
+-----------+---------------+
1 row in set (0.00 sec)
变量 级别 是否可动态 set 作用
log_bin 全局实例 ❌只读 binlog 总开关,整个数据库要不要产生二进制日志
sql_log_bin 会话 session ✅可修改 控制当前这条连接的写入要不要记录到 binlog

3、二进制记录方式

格式 取值 记录内容 优点 缺点
语句模式 STATEMENT 记录执行的原始 SQL 语句 日志体积小,节省磁盘 部分函数 (now ()、rand ()) 主从同步时,从库执行结果和主库不一致,造成数据不一致
行模式 ROW``默认 记录被修改行前后的数据变化,不记录 SQL 数据同步最安全、精准,主从不会出错 日志文件体积大,update 全表会生成大量日志
混合模式 MIXED MySQL 自动判断;安全 SQL 用 STATEMENT,危险函数自动切换 ROW 兼顾体积与安全 少数场景仍有隐患

4、二进制日志配置

变量名 作用 示例值
log_bin binlog 总开关;同时指定日志文件前缀路径;开启 binlog 必须配置 log_bin=binlog
log_bin_basename 只读;binlog 文件完整路径 + 文件名前缀 /var/lib/mysql/binlog
log_bin_index binlog 索引文件 (.index) 路径,记录所有 binlog 文件清单 /var/lib/mysql/binlog.index
server_id 实例唯一编号;开启 binlog / 主从复制必填,不能为 0 server_id=1
sql_log_bin 会话级别开关;控制当前连接写操作要不要写入 binlog SET sql_log_bin=0
binlog_format binlog 记录格式 ROW / STATEMENT / MIXED;8.4 默认 ROW binlog_format=ROW
sync_binlog binlog 刷磁盘策略,安全‑性能最关键参数 sync_binlog=1
binlog_expire_logs_seconds binlog 自动过期时长,单位:秒;替代旧版 expire_logs_days;默认 2592000=30 天 binlog_expire_logs_seconds=604800(7 天)
max_binlog_size 单个 binlog 文件最大容量;到达阈值自动切割生成新文件 max_binlog_size=1G
binlog_checksum 日志校验;CRC32 开启校验 / NONE 关闭 binlog_checksum=CRC32
binlog_row_image ROW 模式记录行镜像;full(新旧完整)/minimal(仅修改字段) binlog_row_image=full
binlog_rows_query_log_events ROW 模式是否把原始 SQL 语句也记录进 binlog OFF

5、查看日志文件内容

bash 复制代码
#必须使用专用工具解析,Linux中的cat\tail\less\more\head都不行
root@MySQL-13:/var/lib/mysql# file binlog.000013
binlog.000013: MySQL replication log, server id 1 MySQL V5+, server version 8.4.11

root@MySQL-13:/var/lib/mysql# mysqlbinlog binlog.000013 -v
# The proper term is pseudo_replica_mode, but we use this compatibility alias
# to make the statement usable on server versions 8.0.24 and older.
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/;
/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
DELIMITER /*!*/;
# at 4
#260826  6:04:37 server id 1  end_log_pos 127 CRC32 0x6280bb29  Start: binlog v 4, server v 8.4.11 created 260826  6:04:37 at startup
# Warning: this binlog is either in use or was not closed properly.
ROLLBACK/*!*/;
BINLOG '
9YGOag8BAAAAewAAAH8AAAABAAQAOC40LjExAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAD1gY5qEwANAAgAAAAABAAEAAAAYwAEGggAAAAAAAACAAAACgoKKioAEjQA
CigAAAEpu4Bi
'/*!*/;
# at 127
#260826  6:04:37 server id 1  end_log_pos 158 CRC32 0x340a5660  Previous-GTIDs
# [empty]
SET @@SESSION.GTID_NEXT= 'AUTOMATIC' /* added by mysqlbinlog */ /*!*/;
DELIMITER ;
# End of log file
/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;
root@MySQL-13:/var/lib/mysql# mysqlbinlog binlog.000013 -vv
# The proper term is pseudo_replica_mode, but we use this compatibility alias
# to make the statement usable on server versions 8.0.24 and older.
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/;
/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
DELIMITER /*!*/;
# at 4
#260826  6:04:37 server id 1  end_log_pos 127 CRC32 0x6280bb29  Start: binlog v 4, server v 8.4.11 created 260826  6:04:37 at startup
# Warning: this binlog is either in use or was not closed properly.
ROLLBACK/*!*/;
BINLOG '
9YGOag8BAAAAewAAAH8AAAABAAQAOC40LjExAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAD1gY5qEwANAAgAAAAABAAEAAAAYwAEGggAAAAAAAACAAAACgoKKioAEjQA
CigAAAEpu4Bi
'/*!*/;
# at 127
#260826  6:04:37 server id 1  end_log_pos 158 CRC32 0x340a5660  Previous-GTIDs
# [empty]
SET @@SESSION.GTID_NEXT= 'AUTOMATIC' /* added by mysqlbinlog */ /*!*/;
DELIMITER ;
# End of log file
/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;
参数 全称 作用举例
‑v --verbose 解析 ROW 格式,输出伪 SQL
‑vv --verbose --verbose 输出修改前 + 修改后的数据,最详细
‑‑start‑datetime --start-datetime 指定开始时间 --start-datetime="2026-08-26 06:00:00"
‑‑stop‑datetime --stop-datetime 指定结束时间
‑‑start‑position --start-position 从指定偏移位置开始解析 --start-position=127
‑‑stop‑position --stop-position 读到指定位置结束
‑d --database 只解析指定库 ‑d hisdbcopy
‑‑base64‑output=decode‑rows 解码行事件(‑v 内部就是开启这个)
‑‑result‑file --result-file 把解析结果导出到文件 --result‑file=/tmp/binlog.sql
‑‑no‑defaults 跳过读取 my.cnf 配置,避免解析报错

6、自定义日志

bash 复制代码
root@MySQL-13:~# mkdir /data/mysql/logs/ -p
root@MySQL-13:~# chown mysql:mysql -R /data/mysql/logs


root@MySQL-13:~# vim /etc/apparmor.d/usr.sbin.mysqld
root@MySQL-13:~# cat /etc/apparmor.d/usr.sbin.mysqld
#include <tunables/global>

# Allow data dir access
  /var/lib/mysql/ r,
  /var/lib/mysql/** rwk,

  /data/mysql/logs/ r,                #新增
  /data/mysql/logs/** rwk,            #新增
# Allow data files dir access

}

root@MySQL-13:~# apparmor_parser -r /etc/apparmor.d/usr.sbin.mysqld
root@MySQL-13:~# vim /etc/mysql/mysql.conf.d/mysqld.cnf
root@MySQL-13:~# cat /etc/mysql/mysql.conf.d/mysqld.cnf

[mysqld]
log_timestamps = SYSTEM
log_bin = /data/mysql/logs/binlog     #新增
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
datadir         = /var/lib/mysql
log-error       = /var/log/mysql/error.log

root@MySQL-13:~# systemctl restart mysql.service
root@MySQL-13:~# ls /data/mysql/logs/
binlog.000001  binlog.index


mysql> show variables like "log%";
+----------------------------------------+----------------------------------------+
| Variable_name                          | Value                                  |
+----------------------------------------+----------------------------------------+
| log_bin                                | ON                                     |
| log_bin_basename                       | /data/mysql/logs/binlog                |
| log_bin_index                          | /data/mysql/logs/binlog.index          |
| log_bin_trust_function_creators        | OFF                                    |
| log_error                              | /var/log/mysql/error.log               |
| log_error_services                     | log_filter_internal; log_sink_internal |                               |
| log_timestamps                         | SYSTEM                                 |
+----------------------------------------+----------------------------------------+
20 rows in set (0.01 sec)

mysql> show binary logs;
+---------------+-----------+-----------+
| Log_name      | File_size | Encrypted |
+---------------+-----------+-----------+
| binlog.000001 |       158 | No        |
+---------------+-----------+-----------+
1 row in set (0.00 sec)

mysql> show binary log status;
+---------------+----------+--------------+------------------+-------------------+
| File          | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+---------------+----------+--------------+------------------+-------------------+
| binlog.000001 |      158 |              |                  |                   |
+---------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)


root@MySQL-13:/var/lib/mysql# cd /data/mysql/logs/
root@MySQL-13:/data/mysql/logs# ls
binlog.000001  binlog.index
root@MySQL-13:/data/mysql/logs# mysqlbinlog binlog.000001 -v
# The proper term is pseudo_replica_mode, but we use this compatibility alias
# to make the statement usable on server versions 8.0.24 and older.
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/;
/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
DELIMITER /*!*/;
# at 4
#260826  6:18:03 server id 1  end_log_pos 127 CRC32 0xf584646f  Start: binlog v 4, server v 8.4.11 created 260826  6:18:03 at startup
# Warning: this binlog is either in use or was not closed properly.
ROLLBACK/*!*/;
BINLOG '
G4WOag8BAAAAewAAAH8AAAABAAQAOC40LjExAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAbhY5qEwANAAgAAAAABAAEAAAAYwAEGggAAAAAAAACAAAACgoKKioAEjQA
CigAAAFvZIT1
'/*!*/;
# at 127
#260826  6:18:03 server id 1  end_log_pos 158 CRC32 0xe039e627  Previous-GTIDs
# [empty]
SET @@SESSION.GTID_NEXT= 'AUTOMATIC' /* added by mysqlbinlog */ /*!*/;
DELIMITER ;
# End of log file
/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;

7、binlog实践

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

mysql> use db1;
Database changed

mysql> CREATE TABLE `student` (
    ->     `id` int(11) NOT NULL AUTO_INCREMENT,
    ->     `name` varchar(255) NOT NULL,
    ->     `age` int(11) NOT NULL,
    ->     `gender` enum('M','F') NOT NULL,
    ->     PRIMARY KEY (`id`)
    -> ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Query OK, 0 rows affected, 3 warnings (0.03 sec)

mysql> insert into student(name,age,gender)values('u11',11,'M'),('u22',22,'F');
Query OK, 2 rows affected (0.05 sec)
Records: 2  Duplicates: 0  Warnings: 0


root@MySQL-13:/data/mysql/logs# ll
-rw-r----- 1 mysql mysql 1589 Aug 26 06:27 binlog.000001
-rw-r----- 1 mysql mysql   31 Aug 26 06:18 binlog.index

#插入文件后日志变大
mysql> insert into student (name,age,gender) values ('u33',33,'M'),('u44',44,'F');
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

root@MySQL-13:/data/mysql/logs# ll
-rw-r----- 1 mysql mysql 1900 Aug 26 06:29 binlog.000001
-rw-r----- 1 mysql mysql   31 Aug 26 06:18 binlog.index

#查看日志文件显示刚才插入的语句
# at 1742
#260826  6:29:11 server id 1  end_log_pos 1804 CRC32 0xd68d5523         Table_map: `db1`.`student` mapped to number 95
# has_generated_invisible_primary_key=0
# at 1804
#260826  6:29:11 server id 1  end_log_pos 1869 CRC32 0x771ba2db         Write_rows: table id 95 flags: STMT_END_F

BINLOG '
t4eOahMBAAAAPgAAAAwHAAAAAF8AAAAAAAEAA2RiMQAHc3R1ZGVudAAEAw8D/gT9AvcBAAEBAAIB
ISNVjdY=
t4eOah4BAAAAQQAAAE0HAAAAAF8AAAAAAAEAAgAE/wADAAAAAwB1MzMhAAAAAQAEAAAAAwB1NDQs
AAAAAtuiG3c=
'/*!*/;
### INSERT INTO `db1`.`student`
### SET
###   @1=3
###   @2='u33'
###   @3=33
###   @4=1
### INSERT INTO `db1`.`student`
### SET
###   @1=4
###   @2='u44'
###   @3=44
###   @4=2
# at 1869
#260826  6:29:11 server id 1  end_log_pos 1900 CRC32 0xeb6f50aa         Xid = 32


#事务未提交前日志不会显示
mysql> begin;
Query OK, 0 rows affected (0.01 sec)

mysql> insert into student (name,age,gender) values ('u55','55','M');
Query OK, 1 row affected (0.01 sec)

# at 1804
#260826  6:29:11 server id 1  end_log_pos 1869 CRC32 0x771ba2db         Write_rows: table id 95 flags: STMT_END_F

BINLOG '
t4eOahMBAAAAPgAAAAwHAAAAAF8AAAAAAAEAA2RiMQAHc3R1ZGVudAAEAw8D/gT9AvcBAAEBAAIB
ISNVjdY=
t4eOah4BAAAAQQAAAE0HAAAAAF8AAAAAAAEAAgAE/wADAAAAAwB1MzMhAAAAAQAEAAAAAwB1NDQs
AAAAAtuiG3c=
'/*!*/;
### INSERT INTO `db1`.`student`
### SET
###   @1=3
###   @2='u33'
###   @3=33
###   @4=1
### INSERT INTO `db1`.`student`
### SET
###   @1=4
###   @2='u44'
###   @3=44
###   @4=2
# at 1869
#260826  6:29:11 server id 1  end_log_pos 1900 CRC32 0xeb6f50aa         


#提交事务后

root@MySQL-13:/data/mysql/logs# ll
-rw-r----- 1 mysql mysql 2196 Aug 26 06:35 binlog.000001
-rw-r----- 1 mysql mysql   31 Aug 26 06:18 binlog.index
root@MySQL-13:/data/mysql/logs# mysqlbinlog binlog.000001 -v
# at 2053
#260826  6:34:19 server id 1  end_log_pos 2115 CRC32 0x99098ac0         Table_map: `db1`.`student` mapped to number 95
# has_generated_invisible_primary_key=0
# at 2115
#260826  6:34:19 server id 1  end_log_pos 2165 CRC32 0xc37d758f         Write_rows: table id 95 flags: STMT_END_F

BINLOG '
64iOahMBAAAAPgAAAEMIAAAAAF8AAAAAAAEAA2RiMQAHc3R1ZGVudAAEAw8D/gT9AvcBAAEBAAIB
IcCKCZk=
64iOah4BAAAAMgAAAHUIAAAAAF8AAAAAAAEAAgAE/wAFAAAAAwB1NTU3AAAAAY91fcM=
'/*!*/;
### INSERT INTO `db1`.`student`
### SET
###   @1=5
###   @2='u55'
###   @3=55
###   @4=1
# at 2165
#260826  6:35:41 server id 1  end_log_pos 2196 CRC32 0x3f24801d         

#按照pos值查看
root@MySQL-13:/data/mysql/logs# mysqlbinlog --start-position=2053 --stop-position=2196 binlog.000001  -v
# The proper term is pseudo_replica_mode, but we use this compatibility alias
# to make the statement usable on server versions 8.0.24 and older.
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/;
/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
DELIMITER /*!*/;
# at 158
#260826  6:18:03 server id 1  end_log_pos 127 CRC32 0xf584646f  Start: binlog v 4, server v 8.4.11 created 260826  6:18:03 at startup
# Warning: this binlog is either in use or was not closed properly.
ROLLBACK/*!*/;
BINLOG '
G4WOag8BAAAAewAAAH8AAAABAAQAOC40LjExAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAbhY5qEwANAAgAAAAABAAEAAAAYwAEGggAAAAAAAACAAAACgoKKioAEjQA
CigAAAFvZIT1
'/*!*/;
# at 2053
#260826  6:34:19 server id 1  end_log_pos 2115 CRC32 0x99098ac0         Table_map: `db1`.`student` mapped to number 95
# at 2115
#260826  6:34:19 server id 1  end_log_pos 2165 CRC32 0xc37d758f         Write_rows: table id 95 flags: STMT_END_F

BINLOG '
64iOahMBAAAAPgAAAEMIAAAAAF8AAAAAAAEAA2RiMQAHc3R1ZGVudAAEAw8D/gT9AvcBAAEBAAIB
IcCKCZk=
64iOah4BAAAAMgAAAHUIAAAAAF8AAAAAAAEAAgAE/wAFAAAAAwB1NTU3AAAAAY91fcM=
'/*!*/;
### INSERT INTO `db1`.`student`
### SET
###   @1=5
###   @2='u55'
###   @3=55
###   @4=1
# at 2165
#260826  6:35:41 server id 1  end_log_pos 2196 CRC32 0x3f24801d         Xid = 34
COMMIT/*!*/;
SET @@SESSION.GTID_NEXT= 'AUTOMATIC' /* added by mysqlbinlog */ /*!*/;
DELIMITER ;
# End of log file
/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;


#导出文件
root@MySQL-13:/data/mysql/logs# mysqlbinlog --start-position=2053 --stop-position=2196 binlog.000001 -v > binlog.sql

root@MySQL-13:/data/mysql/logs# ls
binlog.sql  binlog.000001  binlog.index
root@MySQL-13:/data/mysql/logs# cat binlog.sql
# The proper term is pseudo_replica_mode, but we use this compatibility alias
# to make the statement usable on server versions 8.0.24 and older.
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/;
/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
DELIMITER /*!*/;
# at 158
#260826  6:18:03 server id 1  end_log_pos 127 CRC32 0xf584646f  Start: binlog v 4, server v 8.4.11 created 260826  6                                                                    :18:03 at startup
# Warning: this binlog is either in use or was not closed properly.
ROLLBACK/*!*/;
BINLOG '
G4WOag8BAAAAewAAAH8AAAABAAQAOC40LjExAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAbhY5qEwANAAgAAAAABAAEAAAAYwAEGggAAAAAAAACAAAACgoKKioAEjQA
CigAAAFvZIT1
'/*!*/;
# at 2053
#260826  6:34:19 server id 1  end_log_pos 2115 CRC32 0x99098ac0         Table_map: `db1`.`student` mapped to number                                                                     95
# at 2115
#260826  6:34:19 server id 1  end_log_pos 2165 CRC32 0xc37d758f         Write_rows: table id 95 flags: STMT_END_F

BINLOG '
64iOahMBAAAAPgAAAEMIAAAAAF8AAAAAAAEAA2RiMQAHc3R1ZGVudAAEAw8D/gT9AvcBAAEBAAIB
IcCKCZk=
64iOah4BAAAAMgAAAHUIAAAAAF8AAAAAAAEAAgAE/wAFAAAAAwB1NTU3AAAAAY91fcM=
'/*!*/;
### INSERT INTO `db1`.`student`
### SET
###   @1=5
###   @2='u55'
###   @3=55
###   @4=1
# at 2165
#260826  6:35:41 server id 1  end_log_pos 2196 CRC32 0x3f24801d         Xid = 34
COMMIT/*!*/;
SET @@SESSION.GTID_NEXT= 'AUTOMATIC' /* added by mysqlbinlog */ /*!*/;
DELIMITER ;
# End of log file
/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;
root@MySQL-13:/data/mysql/logs#
字段 含义 运维解释
# at 2053 本条事件起始 Position 偏移位置 恢复数据、截取 binlog 必须用到这个起始坐标
260826 6:34:19 事件发生时间戳 排查什么时候执行的 SQL
server id 1 产生这条 binlog 的 MySQL 实例 ID 主从环境区分是哪台主机生成的日志
end_log_pos 2115 本条事件结束的偏移位置 下一条事件从此位置开始
CRC32 0x99098ac0 日志校验码 开启 binlog‑checksum 后用于校验日志文件有没有损坏
Table_map 表映射事件,库名。表名,映射编号 95 ROW 模式先记录表编号,后面行事件只引用编号,减少日志体积
Write_rows 行写入事件 → 对应 INSERT 操作 Update_rows → 更新Delete_rows → 删除 快速判断是增 / 删 / 改

8、查看二进制日志中的事件

bash 复制代码
show binlog events [IN 'log_name'] [FROM pos] [LIMIT [offset,] row_count];
参数 作用 示例
IN 'log_name' 指定要查看的二进制日志文件名;不写则查看当前正在写入的 binlog 文件 IN 'binlog.000013'
FROM pos 从指定偏移位置(position)开始读取,起始坐标 FROM 2053
LIMIT row_count 限制返回多少条事件 LIMIT 10
LIMIT offset,row_count 跳过 offset 条,再取 row_count 条 LIMIT 5,10
bash 复制代码
mysql> show binlog events from 2053\G
*************************** 1. row ***************************
   Log_name: binlog.000001
        Pos: 2053
 Event_type: Table_map
  Server_id: 1
End_log_pos: 2115
       Info: table_id: 95 (db1.student)
*************************** 2. row ***************************
   Log_name: binlog.000001
        Pos: 2115
 Event_type: Write_rows
  Server_id: 1
End_log_pos: 2165
       Info: table_id: 95 flags: STMT_END_F
*************************** 3. row ***************************
   Log_name: binlog.000001
        Pos: 2165
 Event_type: Xid
  Server_id: 1
End_log_pos: 2196
       Info: COMMIT /* xid=34 */
3 rows in set (0.00 sec)

mysql> show binlog events in 'binlog.000001' from 2053\G
*************************** 1. row ***************************
   Log_name: binlog.000001
        Pos: 2053
 Event_type: Table_map
  Server_id: 1
End_log_pos: 2115
       Info: table_id: 95 (db1.student)
*************************** 2. row ***************************
   Log_name: binlog.000001
        Pos: 2115
 Event_type: Write_rows
  Server_id: 1
End_log_pos: 2165
       Info: table_id: 95 flags: STMT_END_F
*************************** 3. row ***************************
   Log_name: binlog.000001
        Pos: 2165
 Event_type: Xid
  Server_id: 1
End_log_pos: 2196
       Info: COMMIT /* xid=34 */
3 rows in set (0.00 sec)

9、刷新日志文件

bash 复制代码
#刷新方式
  ---关开MySQL或重启
  ---手动刷新

#重启服务
root@MySQL-13:~# systemctl restart mysql.service
root@MySQL-13:~# systemctl restart mysql.service
root@MySQL-13:~# systemctl restart mysql.service
root@MySQL-13:~#

mysql> show binary logs;
+---------------+-----------+-----------+
| Log_name      | File_size | Encrypted |
+---------------+-----------+-----------+
| binlog.000001 |      2219 | No        |
| binlog.000002 |       181 | No        |
| binlog.000003 |       181 | No        |
| binlog.000004 |       158 | No        |
+---------------+-----------+-----------+
4 rows in set (0.00 sec)



#手动
mysql> flush logs;
Query OK, 0 rows affected (0.03 sec)

mysql> flush logs;
Query OK, 0 rows affected (0.02 sec)

mysql> flush logs;
Query OK, 0 rows affected (0.02 sec)

mysql> show binary logs;
+---------------+-----------+-----------+
| Log_name      | File_size | Encrypted |
+---------------+-----------+-----------+
| binlog.000001 |      2219 | No        |
| binlog.000002 |       181 | No        |
| binlog.000003 |       181 | No        |
| binlog.000004 |       202 | No        |
| binlog.000005 |       202 | No        |
| binlog.000006 |       202 | No        |
| binlog.000007 |       158 | No        |
+---------------+-----------+-----------+
7 rows in set (0.00 sec)

10、删除旧日志

bash 复制代码
mysql> purge binary logs to 'binlog.000003';
Query OK, 0 rows affected (0.01 sec)

mysql> show binary logs;
+---------------+-----------+-----------+
| Log_name      | File_size | Encrypted |
+---------------+-----------+-----------+
| binlog.000003 |       181 | No        |
| binlog.000004 |       202 | No        |
| binlog.000005 |       202 | No        |
| binlog.000006 |       202 | No        |
| binlog.000007 |       158 | No        |
+---------------+-----------+-----------+
5 rows in set (0.00 sec)

#删除所有并创建一个新的
mysql> reset binary logs and gtids;
Query OK, 0 rows affected (0.02 sec)

mysql> show binary logs;
+---------------+-----------+-----------+
| Log_name      | File_size | Encrypted |
+---------------+-----------+-----------+
| binlog.000001 |       158 | No        |
+---------------+-----------+-----------+
1 row in set (0.00 sec)

三、通用日志general log

1、什么是通用日志

bash 复制代码
--通用查询日志,用来记录客户端所有到达 MySQL 的 SQL 请求、连接、断开事件

--区别 binlog:
   -binlog:只记录成功提交、修改数据的语句,select 不会记录;用于备份、主从复制
   -general_log:所有 SQL 都记录,select 也记录;用于调试排查问题,默认关闭,生产不要长期开,会占空间。

2、查看运行状态

bash 复制代码
mysql> show variables like "general%";
+------------------+-----------------------------+
| Variable_name    | Value                       |
+------------------+-----------------------------+
| general_log      | OFF                         |
| general_log_file | /var/lib/mysql/MySQL-13.log |
+------------------+-----------------------------+
2 rows in set (0.00 sec)



mysql> set global general_log = 1
    -> ;
Query OK, 0 rows affected (0.01 sec)

mysql> show variables like "general%";
+------------------+-----------------------------+
| Variable_name    | Value                       |
+------------------+-----------------------------+
| general_log      | ON                          |
| general_log_file | /var/lib/mysql/MySQL-13.log |
+------------------+-----------------------------+
2 rows in set (0.00 sec)

root@MySQL-13:~# tail -f /var/lib/mysql/MySQL-13.log
/usr/sbin/mysqld, Version: 8.4.11 (MySQL Community Server - GPL). started with:
Tcp port: 3306  Unix socket: /var/run/mysqld/mysqld.sock
Time                 Id Command    Argument
2026-08-26T07:36:05.559774-00:00            9 Query     show variables like "general%"


mysql> select * from student;
+----+------+-----+--------+
| id | name | age | gender |
+----+------+-----+--------+
|  1 | u11  |  11 | M      |
|  2 | u22  |  22 | F      |
|  3 | u33  |  33 | M      |
|  4 | u44  |  44 | F      |
|  5 | u55  |  55 | M      |
+----+------+-----+--------+
5 rows in set (0.01 sec)


#占空间排查开开启
root@MySQL-13:~# tail -f /var/lib/mysql/MySQL-13.log
/usr/sbin/mysqld, Version: 8.4.11 (MySQL Community Server - GPL). started with:
Tcp port: 3306  Unix socket: /var/run/mysqld/mysqld.sock
Time                 Id Command    Argument
2026-08-26T07:36:05.559774-00:00            9 Query     show variables like "general%"


2026-08-26T07:36:43.180771-00:00            9 Query     select * from student



mysql> set global general_log = 0;
Query OK, 0 rows affected (0.00 sec)

四、慢查询日志 slow query log

1、什么是慢查询日志

bash 复制代码
--慢查询日志用来记录执行耗时超过指定阈值的 SQL 语句,专门用来找出数据库里面执行效率低下、拖慢性能的慢 SQL。
   -select、update、delete、join 查询,只要运行时间超过阈值,都会被记录。

2、查看运行状态

bash 复制代码
#默认10秒会被记录
mysql> show variables like "long_%";
+-----------------+-----------+
| Variable_name   | Value     |
+-----------------+-----------+
| long_query_time | 10.000000 |
+-----------------+-----------+
1 row in set (0.01 sec)

#默认关闭
mysql> show variables like "slow_query%";
+---------------------+----------------------------------+
| Variable_name       | Value                            |
+---------------------+----------------------------------+
| slow_query_log      | OFF                              |
| slow_query_log_file | /var/lib/mysql/MySQL-13-slow.log |
+---------------------+----------------------------------+
2 rows in set (0.00 sec)
变量名 作用 示例值
slow_query_log 慢查询总开关 ON / OFF 默认 OFF
slow_query_log_file 慢查询日志磁盘路径 /var/lib/mysql/xxx‑slow.log
long_query_time 慢查询时间阈值,单位:秒 2(超过 2 秒就算慢 SQL)
log_queries_not_using_indexes 记录没有走索引的 SQL,即使没超时 ON
log_output 输出方式 FILE 文件 / TABLE 表 (mysql.slow_log) FILE

3、修改默认时间和开启

bash 复制代码
#临时开启,永久需要写在配置文件
mysql> set global slow_query_log = 1;
Query OK, 0 rows affected (0.02 sec)

mysql> set global long_query_time = 0.1;
Query OK, 0 rows affected (0.00 sec)


#需要重连会话
mysql> show variables like "long_%";
+-----------------+----------+
| Variable_name   | Value    |
+-----------------+----------+
| long_query_time | 0.100000 |
+-----------------+----------+
1 row in set (0.00 sec)

mysql> show variables like "slow_query%";
+---------------------+----------------------------------+
| Variable_name       | Value                            |
+---------------------+----------------------------------+
| slow_query_log      | ON                               |
| slow_query_log_file | /var/lib/mysql/MySQL-13-slow.log |
+---------------------+----------------------------------+
2 rows in set (0.00 sec)

4、慢日志实操

bash 复制代码
#测试多插入几条数据

mysql> INSERT INTO student(name,age,gender) SELECT CONCAT(name,id), FLOOR(RAND()*20+18),  IF(MOD(id,2)=0,'F','M') FROM student;
Query OK, 16000 rows affected (0.29 sec)  ##大于0.1查看日志
Records: 16000  Duplicates: 0  Warnings: 0


root@MySQL-13:~# tail -f /var/lib/mysql/MySQL-13-slow.log
/usr/sbin/mysqld, Version: 8.4.11 (MySQL Community Server - GPL). started with:
Tcp port: 3306  Unix socket: /var/run/mysqld/mysqld.sock
Time                 Id Command    Argument
# Time: 2026-08-26T07:53:15.456778-00:00
# User@Host: root[root] @ localhost []  Id:    11
# Query_time: 3.364385  Lock_time: 0.000003 Rows_sent: 0  Rows_examined: 0
use slowdb;
SET timestamp=1787730795;
CALL batch_insert_student(1000);
# Time: 2026-08-26T07:55:14.707271-00:00
# User@Host: root[root] @ localhost []  Id:    11
# Query_time: 0.107096  Lock_time: 0.000005 Rows_sent: 0  Rows_examined: 4000
SET timestamp=1787730914;
INSERT INTO student(name,age,gender) SELECT CONCAT(name,id), FLOOR(RAND()*20+18),  IF(MOD(id,2)=0,'F','M') FROM student;
# Time: 2026-08-26T07:55:15.467552-00:00
# User@Host: root[root] @ localhost []  Id:    11
# Query_time: 0.243179  Lock_time: 0.000006 Rows_sent: 0  Rows_examined: 8000
SET timestamp=1787730915;
INSERT INTO student(name,age,gender) SELECT CONCAT(name,id), FLOOR(RAND()*20+18),  IF(MOD(id,2)=0,'F','M') FROM student;
# Time: 2026-08-26T07:55:16.678434-00:00
# User@Host: root[root] @ localhost []  Id:    11
# Query_time: 0.289017  Lock_time: 0.000005 Rows_sent: 0  Rows_examined: 16000
SET timestamp=1787730916;
INSERT INTO student(name,age,gender) SELECT CONCAT(name,id), FLOOR(RAND()*20+18),  IF(MOD(id,2)=0,'F','M') FROM student;

.

5、第三方分析软件

bash 复制代码
 Percona Toolkit

root@MySQL-13:~# apt update && apt install -y gnupg2 wget apt-transport-https curl

root@MySQL-13:~# curl -O https://repo.percona.com/apt/percona-release_latest.generic_all.deb
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 18120  100 18120    0     0   5125      0  0:00:03  0:00:03 --:--:--  5124
root@MySQL-13:~# ls
percona-release_latest.generic_all.deb  
root@MySQL-13:~# dpkg -i percona-release_latest.generic_all.deb

root@MySQL-13:~# apt update

root@MySQL-13:~# apt install -y percona-toolkit

root@MySQL-13:~#  pt-query-digest --version
pt-query-digest 3.2.1

root@MySQL-13:~# pt-query-digest /var/lib/mysql/MySQL-13-slow.log

# 230ms user time, 40ms system time, 27.98M rss, 33.23M vsz
# Current date: Wed Aug 26 08:20:30 2026
# Hostname: MySQL-13
# Files: /var/lib/mysql/MySQL-13-slow.log
# Overall: 4 total, 2 unique, 0.03 QPS, 0.03x concurrency ________________
# Time range: 2026-08-26T07:53:15 to 2026-08-26T07:55:16
# Attribute          total     min     max     avg     95%  stddev  median
# ============     ======= ======= ======= ======= ======= ======= =======
# Exec time             4s   107ms      3s      1s      3s      1s      2s
# Lock time           19us     3us     6us     4us     5us     1us     4us
# Rows sent              0       0       0       0       0       0       0
# Rows examine      27.34k       0  15.62k   6.84k  15.20k   5.61k  11.44k
# Query size           388      31     119      97  118.34   38.17  118.34

# Profile
# Rank Query ID                           Response time Calls R/Call V/M
# ==== ================================== ============= ===== ====== =====
#    1 0xCF2A3A75CE200B0B4E01E8576037FB44  3.3644 84.0%     1 3.3644  0.00 CALL batch_insert_student
#    2 0x9D7907BE639EC3388CC20080B4B24FD2  0.6393 16.0%     3 0.2131  0.03 INSERT SELECT student

# Query 1: 0 QPS, 0x concurrency, ID 0xCF2A3A75CE200B0B4E01E8576037FB44 at byte 0
# This item is included in the report because it matches --limit.
# Scores: V/M = 0.00
# Time range: all events occurred at 2026-08-26T07:53:15
# Attribute    pct   total     min     max     avg     95%  stddev  median
# ============ === ======= ======= ======= ======= ======= ======= =======
# Count         25       1
# Exec time     84      3s      3s      3s      3s      3s       0      3s
# Lock time     15     3us     3us     3us     3us     3us       0     3us
# Rows sent      0       0       0       0       0       0       0       0
# Rows examine   0       0       0       0       0       0       0       0
# Query size     7      31      31      31      31      31       0      31
# String:
# Databases    slowdb
# Hosts        localhost
# Users        root
# Query_time distribution
#   1us
#  10us
# 100us
#   1ms
#  10ms
# 100ms
#    1s  ################################################################
#  10s+
CALL batch_insert_student(1000)\G

# Query 2: 1.50 QPS, 0.32x concurrency, ID 0x9D7907BE639EC3388CC20080B4B24FD2 at byte 1051
# This item is included in the report because it matches --limit.
# Scores: V/M = 0.03
# Time range: 2026-08-26T07:55:14 to 2026-08-26T07:55:16
# Attribute    pct   total     min     max     avg     95%  stddev  median
# ============ === ======= ======= ======= ======= ======= ======= =======
# Count         75       3
# Exec time     15   639ms   107ms   289ms   213ms   279ms    75ms   241ms
# Lock time     84    16us     5us     6us     5us     5us       0     4us
# Rows sent      0       0       0       0       0       0       0       0
# Rows examine 100  27.34k   3.91k  15.62k   9.11k  15.20k   4.70k   7.68k
# Query size    92     357     119     119     119     119       0     119
# String:
# Databases    slowdb
# Hosts        localhost
# Users        root
# Query_time distribution
#   1us
#  10us
# 100us
#   1ms
#  10ms
# 100ms  ################################################################
#    1s
#  10s+
# Tables
#    SHOW TABLE STATUS FROM `slowdb` LIKE 'student'\G
#    SHOW CREATE TABLE `slowdb`.`student`\G
INSERT INTO student(name,age,gender) SELECT CONCAT(name,id), FLOOR(RAND()*20+18),  IF(MOD(id,2)=0,'F','M') FROM student\G
root@MySQL-13:~# pt-query-digest /data/mysql/logs/slow.log
Reading from STDIN ...
^C# Caught SIGINT.
^C# Exiting on SIGINT.
root@MySQL-13:~# ^C
root@MySQL-13:~#
root@MySQL-13:~#
root@MySQL-13:~# pt-query-digest /var/lib/mysql/MySQL-13-slow.log

# 340ms user time, 390ms system time, 27.97M rss, 33.25M vsz
# Current date: Wed Aug 26 08:21:56 2026
# Hostname: MySQL-13
# Files: /var/lib/mysql/MySQL-13-slow.log
# Overall: 4 total, 2 unique, 0.03 QPS, 0.03x concurrency ________________
# Time range: 2026-08-26T07:53:15 to 2026-08-26T07:55:16
# Attribute          total     min     max     avg     95%  stddev  median
# ============     ======= ======= ======= ======= ======= ======= =======
# Exec time             4s   107ms      3s      1s      3s      1s      2s
# Lock time           19us     3us     6us     4us     5us     1us     4us
# Rows sent              0       0       0       0       0       0       0
# Rows examine      27.34k       0  15.62k   6.84k  15.20k   5.61k  11.44k
# Query size           388      31     119      97  118.34   38.17  118.34

# Profile
# Rank Query ID                           Response time Calls R/Call V/M
# ==== ================================== ============= ===== ====== =====
#    1 0xCF2A3A75CE200B0B4E01E8576037FB44  3.3644 84.0%     1 3.3644  0.00 CALL batch_insert_student
#    2 0x9D7907BE639EC3388CC20080B4B24FD2  0.6393 16.0%     3 0.2131  0.03 INSERT SELECT student

# Query 1: 0 QPS, 0x concurrency, ID 0xCF2A3A75CE200B0B4E01E8576037FB44 at byte 0
# This item is included in the report because it matches --limit.
# Scores: V/M = 0.00
# Time range: all events occurred at 2026-08-26T07:53:15
# Attribute    pct   total     min     max     avg     95%  stddev  median
# ============ === ======= ======= ======= ======= ======= ======= =======
# Count         25       1
# Exec time     84      3s      3s      3s      3s      3s       0      3s
# Lock time     15     3us     3us     3us     3us     3us       0     3us
# Rows sent      0       0       0       0       0       0       0       0
# Rows examine   0       0       0       0       0       0       0       0
# Query size     7      31      31      31      31      31       0      31
# String:
# Databases    slowdb
# Hosts        localhost
# Users        root
# Query_time distribution
#   1us
#  10us
# 100us
#   1ms
#  10ms
# 100ms
#    1s  ################################################################
#  10s+
CALL batch_insert_student(1000)\G

# Query 2: 1.50 QPS, 0.32x concurrency, ID 0x9D7907BE639EC3388CC20080B4B24FD2 at byte 1051
# This item is included in the report because it matches --limit.
# Scores: V/M = 0.03
# Time range: 2026-08-26T07:55:14 to 2026-08-26T07:55:16
# Attribute    pct   total     min     max     avg     95%  stddev  median
# ============ === ======= ======= ======= ======= ======= ======= =======
# Count         75       3
# Exec time     15   639ms   107ms   289ms   213ms   279ms    75ms   241ms
# Lock time     84    16us     5us     6us     5us     5us       0     4us
# Rows sent      0       0       0       0       0       0       0       0
# Rows examine 100  27.34k   3.91k  15.62k   9.11k  15.20k   4.70k   7.68k
# Query size    92     357     119     119     119     119       0     119
# String:
# Databases    slowdb
# Hosts        localhost
# Users        root
# Query_time distribution
#   1us
#  10us
# 100us
#   1ms
#  10ms
# 100ms  ################################################################
#    1s
#  10s+
# Tables
#    SHOW TABLE STATUS FROM `slowdb` LIKE 'student'\G
#    SHOW CREATE TABLE `slowdb`.`student`\G
INSERT INTO student(name,age,gender) SELECT CONCAT(name,id), FLOOR(RAND()*20+18),  IF(MOD(id,2)=0,'F','M') FROM student\G
root@MySQL-13:~#

Linux学习之旅之MySQL备份

一、备份基础

1、为什么备份

bash 复制代码
备份本质就是留一份可恢复的副本,出故障后把数据救回来:人为误操作、硬件故障、软件故障、病毒、勒索病毒、恶意删除、业务逻辑 bug等等

2、备份类型

备份类型 含义 备份内容 优点 缺点
全量备份 备份选定范围内所有数据 全部库 / 全部表所有数据 恢复最简单;只需要一份备份文件 备份慢、占用磁盘空间大
增量备份 备份上一次备份(无论全量 / 增量)之后变化的数据 仅新增、修改的数据 每次备份速度快、占用空间小 恢复麻烦:先恢复全量,再依次按顺序恢复每一份增量备份
差异备份 备份距离最近一次全量备份之后变化的数据 自上次全备以来所有改动数据 恢复简单:全量 + 最近一份差异备份 不需要一长串增量链 随着距离全备时间越久,差异包越来越大
部分备份 只备份一部分对象 单个库、单张表、指定几个表 灵活,速度快,省空间 不能恢复整个实例,只能恢复选中对象
类型 别名 业务是否中断锁表 优点 缺点
冷备份 离线备份 必须关闭 MySQL 服务,业务完全中断 原理最简单;备份文件最完整;无锁冲突风险 停机,业务不可用;无法用于 7×24 生产库
温备份 在线锁表备份 数据库不停机,但是会锁表,写入暂停,读可以进行 不用停机;工具原生支持;逻辑备份标准方式 锁表期间 DML 写入被阻塞,高并发业务会卡住
热备份 在线热备 数据库不停机、不锁表,读写完全正常运行 业务无感知,不阻塞读写;适合 7×24 生产环境 实现复杂;需要专用热备工具

3、备份方式

项目 逻辑备份 物理备份
备份产物 SQL 语句文件(CREATE、INSERT) 原始磁盘数据文件 (.ibd、redo log 等)
代表工具 mysqldump、mysqlpump、mydumper xtrabackup、企业备份工具、停机拷贝 data 目录
速度 慢(解析行数据) 快(磁盘块拷贝)
恢复方式 mysql 命令导入执行 SQL 替换数据目录
跨版本迁移 兼容性优秀 兼容性差,版本尽量一致
精细备份 支持单库、单表 xtrabackup 可部分备份;裸拷贝只能整实例

4、逻辑备份和物理备份

对比项 mysqldump(逻辑备份) xtrabackup(物理备份)
备份原理 读取表数据,生成 CREATE/INSERT SQL 语句 直接拷贝 InnoDB 数据文件 + 追 redo log
备份产物 .sql 文本文件 .ibdibdata1、redo log 等原始文件目录
备份速度 慢(逐行读取、组装 SQL) 快(磁盘块级拷贝,几乎不消耗数据库 CPU)
恢复速度 慢(逐条执行 SQL、重建索引) 快(直接放回数据目录,启动即可)
热备支持 --single-transaction 实现 InnoDB 快照热备 原生热备,全程不锁表不阻塞读写
跨版本兼容 强,SQL 文件可恢复到不同小版本 弱,建议恢复到相同大版本 / 相同操作系统
单库 / 单表备份 ✅ 非常灵活 ✅ 支持 --databases 部分备份
增量备份 ❌ 本身不支持增量(靠 binlog 实现) ✅ 原生支持增量备份
适合库大小 中小库(几 G~ 几十 G) 大库(几十 G~ 几百 G 以上)
备份文件可编辑 ✅ 文本可直接查看、修改 ❌ 二进制文件不可编辑
授权性质 MySQL 自带,免费 Percona 开源免费

二、备份实操

1、冷备

环境准备:

bash 复制代码
系统版本:Ubuntu 24.04.4 LTS
数据库版本:MySQL 8.4.11 
数据库安装路径:/var/lib/mysql
主机数量:2台
备份库:MySQL-13;还原库:MySQL-19
bash 复制代码
1. 13和19同时操作一下步骤
root@MYSQL-19:~# mkdir -p /data/mysql/logs/
root@MYSQL-19:~# chown mysql:mysql -R /data/mysql
root@MYSQL-19:~# vim /etc/apparmor.d/usr.sbin.mysqld

# Allow data dir access
  /var/lib/mysql/ r,
  /var/lib/mysql/** rwk,

  /data/mysql/logs/ r,        #新增
  /data/mysql/logs/** rwk,        #新增
root@MYSQL-19:~# apparmor_parser -r /etc/apparmor.d/usr.sbin.mysqld
root@MYSQL-19:~# systemctl restart mysql.service

mysql> show variables like 'log_bin';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_bin       | ON    |
+---------------+-------+
1 row in set (0.00 sec)

2. 13上创建测试库和表

mysql> create database db1;
use db1;
CREATE TABLE student (
 id int NOT NULL AUTO_INCREMENT,
 name varchar(255) NOT NULL,
 age int NOT NULL,
 gender enum('M','F') NOT NULL,
 PRIMARY KEY (id)
);
insert into student(name,age,gender)values('u11',11,'M'),('u22',22,'F');
insert into student(name,age,gender)values('u33',13,'M'),('u44',24,'F');Query OK, 1 row affected (0.01 sec)

mysql> use db1;
Database changed
mysql> CREATE TABLE student (
    ->  id int NOT NULL AUTO_INCREMENT,
    ->  name varchar(255) NOT NULL,
    ->  age int NOT NULL,
    ->  gender enum('M','F') NOT NULL,
    ->  PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.03 sec)

mysql> insert into student(name,age,gender)values('u11',11,'M'),('u22',22,'F');
Query OK, 2 rows affected (0.02 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> insert into student(name,age,gender)values('u33',13,'M'),('u44',24,'F');
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> show tables from db1;
+---------------+
| Tables_in_db1 |
+---------------+
| student       |
+---------------+
1 row in set (0.00 sec)

mysql> select count(*) from db1.student;
+----------+
| count(*) |
+----------+
|        4 |
+----------+
1 row in set (0.01 sec)


3. 13关闭MySQL备份
root@MySQL-13:~# systemctl stop mysql.service
root@MySQL-13:~# mkdir -p /data/backup
root@MySQL-13:~# tar czf /data/backup/mysql_datadir.tar.gz /var/lib/mysql
tar: Removing leading `/' from member names
root@MySQL-13:~# tar czf /data/backup/mysql_binlog.tar.gz /data/mysql/logs/
tar: Removing leading `/' from member names
root@MySQL-13:~# ls /data/backup/
mysql_binlog.tar.gz  mysql_datadir.tar.gz


4. 13开启MySQL插入数据

root@MySQL-13:~# systemctl start mysql.service
mysql> insert into db1.student(name,age,gender) values('u55',25,'M'),('u66',26,'F');
Query OK, 2 rows affected (0.10 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select count(8) from db1.student;
+----------+
| count(8) |
+----------+
|        6 |
+----------+
1 row in set (0.00 sec)

5. 19关闭MySQL服务还原数据


root@MYSQL-19:~# systemctl stop mysql.service
root@MYSQL-19:~# rm -rf /var/lib/mysql/*
root@MYSQL-19:~# rm -rf /data/mysql/logs/*

root@MYSQL-19:~# mkdir -p /data/backup
root@MYSQL-19:~# scp root@10.0.0.13:/data/backup/* /data/backup/
The authenticity of host '10.0.0.13 (10.0.0.13)' can't be 
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.0.0.13' (ED25519) to the list of known hosts.
root@10.0.0.13's password:
mysql_binlog.tar.gz                                         100%  370KB   9.4MB/s   00:00
mysql_datadir.tar.gz                                        100% 3180KB  17.8MB/s   00:00
root@MYSQL-19:~# cd /data/backup/
root@MYSQL-19:/data/backup# ls
mysql_binlog.tar.gz  mysql_datadir.tar.gz


root@MYSQL-19:/data/backup# tar xf mysql_binlog.tar.gz
root@MYSQL-19:/data/backup# tar xf mysql_datadir.tar.gz
root@MYSQL-19:/data/backup# ls
data  mysql_binlog.tar.gz  mysql_datadir.tar.gz  var
root@MYSQL-19:/data/backup# ls data/mysql/logs/
binlog.000001  binlog.000002  binlog.index  binlog.sql
root@MYSQL-19:/data/backup# ls var/lib/
mysql
root@MYSQL-19:/data/backup# mv var/lib/mysql/* /var/lib/mysql/
root@MYSQL-19:/data/backup# mv data/mysql/logs/* /data/mysql/logs/

root@MYSQL-19:/data/backup# chown mysql:mysql /var/lib/mysql
root@MYSQL-19:/data/backup# chown mysql:mysql /data/mysql

6. 19开启MySQL验证

root@MYSQL-19:/data/backup# systemctl start mysql.service
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| db1                |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.02 sec)

mysql> select count(*) from db1.student;
+----------+
| count(*) |
+----------+
|        4 |
+----------+
1 row in set (0.01 sec)


7. 19还原增量备份

#13有三个二进制文件,备份开启后生成了一个新的0003,新插入的数据在0003中
root@MySQL-13:~# ll /data/mysql/logs/
-rw-r----- 1 mysql mysql 1222514 Aug 26 09:38 binlog.000001
-rw-r----- 1 mysql mysql    1674 Aug 27 01:31 binlog.000002
-rw-r----- 1 mysql mysql     468 Aug 27 01:34 binlog.000003
-rw-r----- 1 mysql mysql      93 Aug 27 01:34 binlog.index

#19缺少13中插入的数据
root@MYSQL-19:/data/backup# ll /data/mysql/logs/
-rw-r----- 1 mysql mysql 1222514 Aug 26 09:38 binlog.000001
-rw-r----- 1 mysql mysql    1674 Aug 27 01:31 binlog.000002
-rw-r----- 1 mysql mysql      62 Aug 27 01:13 binlog.index

8. 19强取豪夺需要的文件
root@MYSQL-19:/data/backup# scp root@10.0.0.13:/data/mysql/logs/binlog.000003 ./
root@10.0.0.13's password:
binlog.000003                                               100%  468   107.2KB/s   00:00
root@MYSQL-19:/data/backup# ls
binlog.000003  


9. 查看二进制文件找到需要的数据

root@MYSQL-19:/data/backup# mysqlbinlog binlog.000003 -v
# The proper term is pseudo_replica_mode, but we use this compatibility alias
# to make the statement usable on server versions 8.0.24 and older.
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/;
/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
DELIMITER /*!*/;
# at 4
#260827  1:34:02 server id 1  end_log_pos 127 CRC32 0xeb61de56  Start: binlog v 4, server v 8.4.11 created 260827  1:34:02 at startup
# Warning: this binlog is either in use or was not closed properly.
ROLLBACK/*!*/;
BINLOG '
CpSPag8BAAAAewAAAH8AAAABAAQAOC40LjExAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAKlI9qEwANAAgAAAAABAAEAAAAYwAEGggAAAAAAAACAAAACgoKKioAEjQA
CigAAAFW3mHr
'/*!*/;
# at 127
#260827  1:34:02 server id 1  end_log_pos 158 CRC32 0x38053bd2  Previous-GTIDs
# [empty]
# at 158
#260827  1:34:33 server id 1  end_log_pos 237 CRC32 0x7534e445  Anonymous_GTID  last_committed=0      sequence_number=1       rbr_only=yes    original_committed_timestamp=1787794473337425immediate_commit_timestamp=1787794473337425      transaction_length=310
/*!50718 SET TRANSACTION ISOLATION LEVEL READ COMMITTED*//*!*/;
# original_commit_timestamp=1787794473337425 (2026-08-27 01:34:33.337425 UTC)
# immediate_commit_timestamp=1787794473337425 (2026-08-27 01:34:33.337425 UTC)
/*!80001 SET @@session.original_commit_timestamp=1787794473337425*//*!*/;
/*!80014 SET @@session.original_server_version=80411*//*!*/;
/*!80014 SET @@session.immediate_server_version=80411*//*!*/;
SET @@SESSION.GTID_NEXT= 'ANONYMOUS'/*!*/;
# at 237
#260827  1:34:33 server id 1  end_log_pos 308 CRC32 0x8b774280  Query   thread_id=11    exec_time=0   error_code=0
SET TIMESTAMP=1787794473/*!*/;
SET @@session.pseudo_thread_id=11/*!*/;
SET @@session.foreign_key_checks=1, @@session.sql_auto_is_null=0, @@session.unique_checks=1, @@session.autocommit=1/*!*/;
SET @@session.sql_mode=1168113696/*!*/;
SET @@session.auto_increment_increment=1, @@session.auto_increment_offset=1/*!*/;
/*!\C utf8mb4 *//*!*/;
SET @@session.character_set_client=255,@@session.collation_connection=255,@@session.collation_server=255/*!*/;
SET @@session.lc_time_names=0/*!*/;
SET @@session.collation_database=DEFAULT/*!*/;
/*!80011 SET @@session.default_collation_for_utf8mb4=255*//*!*/;
BEGIN
/*!*/;
# at 308
#260827  1:34:33 server id 1  end_log_pos 372 CRC32 0x997f6687  Table_map: `db1`.`student` mapped to number 83
# has_generated_invisible_primary_key=0
# at 372
#260827  1:34:33 server id 1  end_log_pos 437 CRC32 0x29060c6e  Write_rows: table id 83 flags: STMT_END_F

BINLOG '
KZSPahMBAAAAQAAAAHQBAAAAAFMAAAAAAAEAA2RiMQAHc3R1ZGVudAAEAw8D/gT8A/cBAAEBAAID
/P8Ah2Z/mQ==
KZSPah4BAAAAQQAAALUBAAAAAFMAAAAAAAEAAgAE/wAFAAAAAwB1NTUZAAAAAQAGAAAAAwB1NjYa
AAAAAm4MBik=
'/*!*/;
### INSERT INTO `db1`.`student`
### SET
###   @1=5
###   @2='u55'
###   @3=25
###   @4=1
### INSERT INTO `db1`.`student`
### SET
###   @1=6
###   @2='u66'
###   @3=26
###   @4=2
# at 437
#260827  1:34:33 server id 1  end_log_pos 468 CRC32 0x6e5d0046  Xid = 4
COMMIT/*!*/;
SET @@SESSION.GTID_NEXT= 'AUTOMATIC' /* added by mysqlbinlog */ /*!*/;
DELIMITER ;
# End of log file
/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;


#可以观察到文件内容# at 237后面几行有BEGIN事务开启,# at 437后有一个end_log_pos 468值和COMMIT/*!*/;事务提交,所以我们需要237到468的数据,里面刚好有新增的数据55和66.

10. 新增数据恢复并验证

root@MYSQL-19:/data/backup# mysqlbinlog --start-position=237 --stop-position=468 binlog.000003 | mysql -uroot -pXyx@123456
mysql: [Warning] Using a password on the command line interface can be insecure.

mysql> \r
Connection id:    11
Current database: *** NONE ***

mysql> select count(*) from db1.student;
+----------+
| count(*) |
+----------+
|        6 |
+----------+
1 row in set (0.00 sec)

2、 mysqldump 逻辑热备份

环境准备:

bash 复制代码
系统版本:Ubuntu 24.04.4 LTS
数据库版本:MySQL 8.4.11 
数据库安装路径:/var/lib/mysql
主机数量:2台
备份库:MySQL-13;还原库:MySQL-19
bash 复制代码
mysql> drop database db1;
Query OK, 1 row affected (0.04 sec)

mysql> create database db1;
Query OK, 1 row affected (0.01 sec)

mysql> create database db2;
Query OK, 1 row affected (0.00 sec)

mysql> use db1;
Database changed
mysql> CREATE TABLE student (
    ->   id int NOT NULL AUTO_INCREMENT,
    ->   name varchar(255) NOT NULL,
    ->   age int NOT NULL,
    ->   gender enum('M','F') NOT NULL,
    ->   PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.03 sec)

mysql> insert into student(name,age,gender)values('u11',11,'M'),('u22',22,'F'),
    -> ('u33',33,'M'),('u44',44,'F');
Query OK, 4 rows affected (0.01 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> use db2;
Database changed
mysql> create table student select * from db1.student;
Query OK, 4 rows affected (0.05 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> create table student2 select * from db1.student;
Query OK, 4 rows affected (0.03 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> create table student3 select * from db1.student;
Query OK, 4 rows affected (0.04 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> insert into student(name,age,gender) values("db2-user1",55,'M');
Query OK, 1 row affected (0.01 sec)

mysql> insert into student2(name,age,gender) values("db2-user2",55,'M');
Query OK, 1 row affected (0.00 sec)

mysql> insert into student3(name,age,gender) values("db2-user3",55,'M');
Query OK, 1 row affected (0.01 sec)

mysql> show databases like "db%";
+----------------+
| Database (db%) |
+----------------+
| db1            |
| db2            |
+----------------+
2 rows in set (0.00 sec)

备份开始

bash 复制代码
#-A备份所有数据(创建库、表、数据)
root@MySQL-13:~# mysqldump -uroot -pXyx@123456 -S /var/run/mysqld/mysqld.sock -A > /data/backu                  p/all_db_bak_$(date +%F).sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.

#没有加-B备份db1库所有表,恢复时需要建库在恢复
root@MySQL-13:~# mysqldump -u root -pXyx@123456 -S /var/run/mysqld/mysqld.sock \
--single-transaction --source-data=2 \
db1 > /data/backup/db1_$(date +%F).sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.

#加-B指定库db1备份,也可以多库-B db1 db2
root@MySQL-13:~# mysqldump -u root -pXyx@123456 -S /var/run/mysqld/mysqld.sock \
--single-transaction --source-data=2 \
-B db1 > /data/backup/db1_$(date +%F).sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.

#不加-B 库名 表名,只备份指定库的指定表
root@MySQL-13:~# mysqldump -u root -pXyx@123456 -S /var/run/mysqld/mysqld.sock \
--single-transaction --source-data=2 \
db1 student > /data/backup/db1_student_$(date +%F).sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.


root@MySQL-13:~# ls /data/backup/*.sql
/data/backup/all_db_bak_2026-08-27.sql
/data/backup/db1_2026-08-27.sql         /data/backup/db1_student_2026-08-27.sql
root@MySQL-13:~#

恢复开始

bash 复制代码
#恢复所有库
root@MYSQL-19:/data/backup# mysql -S /var/run/mysqld/mysqld.sock  < all_db_bak_2026-08-27.sql

#恢复指定库
mysql> drop database db1;
Query OK, 0 rows affected (0.01 sec)

mysql> source /data/backup/db1_2026-08-27.sql
Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 1 row affected (0.01 sec)

Database changed
Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.03 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.01 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 4 rows affected (0.01 sec)
Records: 4  Duplicates: 0  Warnings: 0

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.01 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

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


mysql> show tables from db1;
+---------------+
| Tables_in_db1 |
+---------------+
| student       |
+---------------+
1 row in set (0.00 sec)


#恢复指定表
mysql> use db1;
Database changed
mysql> drop table student;
Query OK, 0 rows affected (0.01 sec)

mysql> show tables;
Empty set (0.01 sec)

mysql> source /data/backup/db1_student_2026-08-27.sql;
Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.01 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.01 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.01 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.01 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.03 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.01 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 4 rows affected (0.01 sec)
Records: 4  Duplicates: 0  Warnings: 0

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.01 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| student       |
+---------------+
1 row in set (0.01 sec)

3、XtraBackup 物理热备份

环境准备

bash 复制代码
系统版本:Ubuntu 24.04.4 LTS
数据库版本:MySQL 8.4.11 
数据库安装路径:/var/lib/mysql
主机数量:2台
备份库:MySQL-13;还原库:MySQL-19

#13和19安装软件和创建用户
root@MYSQL-19:/data/backup# apt update

root@MYSQL-19:/data/backup# apt install curl -y

root@MYSQL-19:/data/backup# curl -O https://repo.percona.com/apt/percona-release_latest.generic_all.deb

root@MYSQL-19:/data/backup# apt install gnupg2 lsb-release ./percona-release_latest.generic_all.deb -y

root@MYSQL-19:/data/backup# apt update

root@MYSQL-19:/data/backup# percona-release enable pxb-84-lts release --scheme https

root@MYSQL-19:/data/backup# apt install percona-xtrabackup-84 lz4 zstd -y

root@MYSQL-19:/data/backup# xtrabackup --version
2026-08-27T04:26:26.088235-00:00 0 [Note] [MY-011825] [Xtrabackup] recognized server arguments: --datadir=/var/lib/mysql
xtrabackup version 8.4.0-6 based on MySQL server 8.4.0 Linux (x86_64) (revision id: 46a895ed)


root@MySQL-13:~# mysql
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 20
Server version: 8.4.11 MySQL Community Server - GPL

Copyright (c) 2000, 2026, 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.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> CREATE USER 'bkpuser'@'localhost' IDENTIFIED BY 'Xyx@1234';
Query OK, 0 rows affected (0.18 sec)

mysql> GRANT BACKUP_ADMIN, PROCESS, RELOAD, LOCK TABLES, REPLICATION CLIENT ON *.* TO 'bkpuser'@'localhost';
Query OK, 0 rows affected (0.02 sec)

mysql> GRANT SELECT ON performance_schema.log_status TO 'bkpuser'@'localhost';
Query OK, 0 rows affected (0.07 sec)

mysql> GRANT SELECT ON performance_schema.keyring_component_status TO 'bkpuser'@'localhost';
Query OK, 0 rows affected (0.01 sec)

mysql> GRANT SELECT ON performance_schema.replication_group_members TO 'bkpuser'@'localhost';
Query OK, 0 rows affected (0.01 sec)

mysql> GRANT CREATE,ALTER,INSERT,SELECT ON PERCONA_SCHEMA.xtrabackup_history TO 'bkpuser'@'localhost';
Query OK, 0 rows affected (0.01 sec)

mysql> GRANT CREATE TABLESPACE ON *.* TO 'bkpuser'@'localhost';
Query OK, 0 rows affected (0.01 sec)

mysql>
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.01 sec)

mysql>
mysql> SHOW GRANTS FOR 'bkpuser'@'localhost';
+-----------------------------------------------------------------------------------------------------------+
| Grants for bkpuser@localhost                                                                              |
+-----------------------------------------------------------------------------------------------------------+
| GRANT RELOAD, PROCESS, LOCK TABLES, REPLICATION CLIENT, CREATE TABLESPACE ON *.* TO `bkpuser`@`localhost` |
| GRANT BACKUP_ADMIN ON *.* TO `bkpuser`@`localhost`                                                        |
| GRANT SELECT, INSERT, CREATE, ALTER ON `PERCONA_SCHEMA`.`xtrabackup_history` TO `bkpuser`@`localhost`     |
| GRANT SELECT ON `performance_schema`.`keyring_component_status` TO `bkpuser`@`localhost`                  |
| GRANT SELECT ON `performance_schema`.`log_status` TO `bkpuser`@`localhost`                                |
| GRANT SELECT ON `performance_schema`.`replication_group_members` TO `bkpuser`@`localhost`                 |
+-----------------------------------------------------------------------------------------------------------+
6 rows in set (0.00 sec)

mysql>
mysql> SHOW PRIVILEGES;
+------------------------------+---------------------------------------+-----------------------------------------------------------------+
| Privilege                    | Context                               | Comment                                                         |
+------------------------------+---------------------------------------+-----------------------------------------------------------------+
| Alter                        | Tables                                | To alter the table                                              |
| Alter routine                | Functions,Procedures                  |...........................
| FLUSH_USER_RESOURCES         | Server Admin                          |                                                                 |
| FLUSH_TABLES                 | Server Admin                          |                                                                 |
+------------------------------+---------------------------------------+-----------------------------------------------------------------+
73 rows in set (0.01 sec)


mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| db1                |
| db2                |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
6 rows in set (0.03 sec)

mysql> show tables from db1;
+---------------+
| Tables_in_db1 |
+---------------+
| student       |
+---------------+
1 row in set (0.01 sec)

mysql> show tables from db2;
+---------------+
| Tables_in_db2 |
+---------------+
| student       |
| student2      |
| student3      |
+---------------+
3 rows in set (0.01 sec)

全量备份

bash 复制代码
#备份测试
root@MySQL-13:~# xtrabackup --user=bkpuser --password='Xyx@1234' \
-S /var/run/mysqld/mysqld.sock \
--backup \
--target-dir=/data/backup/xtra_test
2026-08-27T04:45:16.629883-00:00 0 [Note] [MY-011825] [Xtrabackup] recognized server arguments: --log_bin=/data/mysql/logs/binlog --datadir=/var/lib/mysql
2026-08-27T04:45:16.630122-00:00 0 [Note] [MY-011825] [Xtrabackup] recognized client arguments: --user=bkpuser --password=* --socket=/var/run/mysqld/mysqld.sock --backup=1 --target-dir=/data/backup/xtra_test
xtrabackup version 8.4.0-6 based on MySQL server 8.4.0 Linux (x86_64) (revision id: 46a895ed)

root@MySQL-13:~# ls /data/backup/xtra_test/
backup-my.cnf  db1             ibdata1    performance_schema  undo_002                xtrabackup_info
binlog.000004  db2             mysql      sys                 xtrabackup_binlog_info  xtrabackup_logfile
binlog.index   ib_buffer_pool  mysql.ibd  undo_001            xtrabackup_checkpoints  xtrabackup_tablespaces
root@MySQL-13:~#



1. 全量备份

root@MySQL-13:~# xtrabackup --user=bkpuser --password='Xyx@1234' \
-S /var/run/mysqld/mysqld.sock \
--backup --target-dir=/backup/base
2026-08-27T05:47:56.933385-00:00 0 [Note] [MY-011825] [Xtrabackup] recognized server arguments: --log_bin=/data/mysql/logs/binlog --datadir=/var/lib/mysql

root@MySQL-13:~# ls /backup/base/
backup-my.cnf  db1             ibdata1    performance_schema  undo_002                xtrabackup_info
binlog.000008  db2             mysql      sys                 xtrabackup_binlog_info  xtrabackup_logfile
binlog.index   ib_buffer_pool  mysql.ibd  undo_001            xtrabackup_checkpoints  xtrabackup_tablespaces
root@MySQL-13:~#


2. 恢复数据库


root@MYSQL-19:~# systemctl stop mysql.service
root@MYSQL-19:~# rm -rf /var/lib/mysql/*
root@MYSQL-19:~# rm -rf /data/mysql/logs/*
root@MYSQL-19:~# rm -rf /data/backup/*

root@MYSQL-19:~# scp -r root@10.0.0.13:/backup/* /data/backup/
root@10.0.0.13's password:

root@MYSQL-19:~# ls /data/backup/
base

#未提交的事务回滚
root@MYSQL-19:~# xtrabackup --prepare --target-dir=/data/backup/base

#还原数据

root@MYSQL-19:~# xtrabackup --copy-back --target-dir=/data/backup/base --datadir=/var/lib/mysql
2026-08-27T05:52:59.293004-00:00 0 [Note] [MY-011825] [Xtrabackup] recognized server arguments: --datadir=/var/lib/mysql --datadir=/var/lib/mysql


root@MYSQL-19:~# chown mysql:mysql /data/mysql/ -R
root@MYSQL-19:~# chown mysql:mysql /var/lib/mysql -R
root@MYSQL-19:~# systemctl start mysql.service


3. 验证
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| db1                |
| db2                |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
6 rows in set (0.07 sec)

mysql> show tables from db1;
+---------------+
| Tables_in_db1 |
+---------------+
| student       |
+---------------+
1 row in set (0.02 sec)

mysql> show tables from db2;
+---------------+
| Tables_in_db2 |
+---------------+
| student       |
| student2      |
| student3      |
+---------------+
3 rows in set (0.01 sec)

增量备份

bashroot@MYSQL-19:~# 复制代码
1. 先全量备份

root@MySQL-13:~# rm -rf /backup/*
root@MySQL-13:~# ls /backup/
root@MySQL-13:~# xtrabackup --user=bkpuser --password='Xyx@1234' \
-S /var/run/mysqld/mysqld.sock \
--backup --target-dir=/backup/base

2. 插入新的数据并第一次增量备份
mysql> insert into db1.student (name,age,gender) values('u77',77,'M');
Query OK, 1 row affected (0.02 sec)


root@MySQL-13:~# xtrabackup --user=bkpuser --password='Xyx@1234' \
-S /var/run/mysqld/mysqld.sock \
--backup --target-dir=/backup/inc1 --incremental-basedir=/backup/base

3. 插入新的数据并第二次增量备份

mysql> insert into db1.student (name,age,gender) values('u88',88,'F');
Query OK, 1 row affected (0.00 sec)

root@MySQL-13:~# xtrabackup --user=bkpuser --password='Xyx@1234' \
-S /var/run/mysqld/mysqld.sock \
--backup --target-dir=/backup/inc2 --incremental-basedir=/backup/inc1

mysql> select count(*) from db1.student;
+----------+
| count(*) |
+----------+
|        6 |
+----------+
1 row in set (0.01 sec)

mysql> select * from db1.student;
+----+------+-----+--------+
| id | name | age | gender |
+----+------+-----+--------+
|  1 | u11  |  11 | M      |
|  2 | u22  |  22 | F      |
|  3 | u33  |  33 | M      |
|  4 | u44  |  44 | F      |
|  5 | u77  |  77 | M      |
|  6 | u88  |  88 | F      |
+----+------+-----+--------+
6 rows in set (0.00 sec)


4. 查看备份文件并拷贝到19主机
root@MySQL-13:~# ls /backup/
base  inc1  inc2
root@MySQL-13:~# du -sh /backup/*
73M     /backup/base
2.1M    /backup/inc1
2.1M    /backup/inc2


root@MYSQL-19:~# rm -rf /data/backup/*
root@MYSQL-19:~# scp -r root@10.0.0.13:/backup/* /data/backup/
root@10.0.0.13's password:
root@MYSQL-19:~# ls /data/backup/
base  inc1  inc2
root@MYSQL-19:~# du -sh /data/backup/*
73M     /data/backup/base
2.1M    /data/backup/inc1
2.1M    /data/backup/inc2

5. 重做三次备份文件
root@MYSQL-19:~# xtrabackup --prepare --apply-log-only --target-dir=/data/backup/base

root@MYSQL-19:~# xtrabackup --prepare --apply-log-only --target-dir=/data/backup/base --incremental-dir=/data/backup/inc1

root@MYSQL-19:~# xtrabackup --prepare --target-dir=/data/backup/base --incremental-dir=/data/backup/inc2


root@MYSQL-19:~# du -sh /data/backup/*
93M     /data/backup/base
11M     /data/backup/inc1
35M     /data/backup/inc2


6. 关闭服务删除旧数据并恢复数据

root@MYSQL-19:~# systemctl stop mysql.service
root@MYSQL-19:~# rm -rf /var/lib/mysql/*
root@MYSQL-19:~# rm -rf /data/mysql/logs/*
root@MYSQL-19:~# xtrabackup --copy-back --target-dir=/data/backup/base --datadir=/var/lib/mysql

7. 开启服务并验证

root@MYSQL-19:~# chown -R mysql:mysql /var/lib/mysql /data/mysql/logs
root@MYSQL-19:~# systemctl start mysql.service

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| db1                |
| db2                |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
6 rows in set (0.02 sec)

mysql> select count(*) from db1.student;
+----------+
| count(*) |
+----------+
|        6 |
+----------+
1 row in set (0.02 sec)

mysql> select * from db1.student;
+----+------+-----+--------+
| id | name | age | gender |
+----+------+-----+--------+
|  1 | u11  |  11 | M      |
|  2 | u22  |  22 | F      |
|  3 | u33  |  33 | M      |
|  4 | u44  |  44 | F      |
|  5 | u77  |  77 | M      |
|  6 | u88  |  88 | F      |
+----+------+-----+--------+
6 rows in set (0.00 sec)

4、Binlog 时间点数据恢复

环境准备

bash 复制代码
系统版本:Ubuntu 24.04.4 LTS
数据库版本:MySQL 8.4.11 
数据库安装路径:/var/lib/mysql
主机数量:2台
备份库:MySQL-13;还原库:MySQL-19
mysql> use db1;
Database changed
mysql> CREATE TABLE ruoyi_user(
    -> id INT PRIMARY KEY AUTO_INCREMENT,
    -> username VARCHAR(50),
    -> phone VARCHAR(20)
    -> );
INSERT INTO ruoyi_user(username,phone) VALUES
('admin','13800138000'),
('test','13900139000'),
('zhangsan','13700137000');
select * from ruoyi_user;Query OK, 0 rows affected (0.06 sec)

mysql> INSERT INTO ruoyi_user(username,phone) VALUES
    -> ('admin','13800138000'),
    -> ('test','13900139000'),
    -> ('zhangsan','13700137000');
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from ruoyi_user;
+----+----------+-------------+
| id | username | phone       |
+----+----------+-------------+
|  1 | admin    | 13800138000 |
|  2 | test     | 13900139000 |
|  3 | zhangsan | 13700137000 |
+----+----------+-------------+
3 rows in set (0.00 sec)

mysql> reset binary logs and gtids;
Query OK, 0 rows affected (0.04 sec)

mysql> SHOW BINARY LOG STATUS;
+---------------+----------+--------------+------------------+-------------------+
| File          | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+---------------+----------+--------------+------------------+-------------------+
| binlog.000001 |      158 |              |                  |                   |
+---------------+----------+--------------+------------------+-------------------+
1 row in set (0.01 sec)

开始备份

bash 复制代码
1. 13备份数据
root@MySQL-13:~# xtrabackup --user=bkpuser --password='Xyx@1234' \
-S /var/run/mysqld/mysqld.sock \
--backup --target-dir=/backup/inc1 --incremental-basedir=/backup/base

root@MySQL-13:~# cat /backup/base/xtrabackup_binlog_info
binlog.000002   158
root@MySQL-13:~# ls /data/mysql/logs/
binlog.000001  binlog.000002  binlog.index  binlog.sql


mysql> show binary logs;
+---------------+-----------+-----------+
| Log_name      | File_size | Encrypted |
+---------------+-----------+-----------+
| binlog.000001 |       202 | No        |
| binlog.000002 |      1494 | No        |
+---------------+-----------+-----------+


2. 19恢复数据
root@MYSQL-19:~# systemctl stop mysql.service
root@MYSQL-19:~# rm -rf /data/backup/*
root@MYSQL-19:~# rm -rf /var/lib/mysql/*
root@MYSQL-19:~# rm -rf /data/mysql/logs/*
root@MYSQL-19:~# scp root@10.0.0.13:/backup/* /data/backup/
root@10.0.0.13's password:
root@MYSQL-19:~# scp -r root@10.0.0.13:/backup/* /data/backup/
root@10.0.0.13's password:


root@MYSQL-19:~# xtrabackup --prepare --target-dir=/data/backup/base
root@MYSQL-19:~# xtrabackup --copy-back --target-dir=/data/backup/base --datadir=/var/lib/mysql

root@MYSQL-19:~# chown mysql:mysql -R /data/mysql/ /var/lib/
root@MYSQL-19:~# systemctl start mysql.service


3. 19验证数据

mysql> show tables from db1;
+---------------+
| Tables_in_db1 |
+---------------+
| ruoyi_user    |
| student       |
+---------------+
2 rows in set (0.02 sec)


4. 13新增更新删除数据

mysql> INSERT INTO ruoyi_user(username,phone) VALUES ('lisi','13600136000'),('wangwu','13500135000');
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> UPDATE ruoyi_user SET phone='13800000000' WHERE username='admin';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> delete from ruoyi_user where id in (1,2);
Query OK, 2 rows affected (0.00 sec)

mysql> INSERT INTO ruoyi_user(username,phone) VALUES ('zhaoliu','13400134000'),('qianqi','13300133000');
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> show binary log status;
+---------------+----------+--------------+------------------+-------------------+
| File          | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+---------------+----------+--------------+------------------+-------------------+
| binlog.000002 |     1494 |              |                  |                   |
+---------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

mysql> select * from ruoyi_user;
+----+----------+-------------+
| id | username | phone       |
+----+----------+-------------+
|  3 | zhangsan | 13700137000 |
|  4 | lisi     | 13600136000 |
|  5 | wangwu   | 13500135000 |
|  6 | zhaoliu  | 13400134000 |
|  7 | qianqi   | 13300133000 |
+----+----------+-------------+
5 rows in set (0.00 sec)


root@MySQL-13:~# mysqlbinlog /data/mysql/logs/binlog.000002 -v

# at 237
#260828  3:54:02 server id 1  end_log_pos 311 CRC32 0xeff3b567  Query   thread_id=17    exec_time=0     error_code=0
SET TIMESTAMP=1787889242/*!*/;
SET @@session.pseudo_thread_id=17/*!*/;
SET @@session.foreign_key_checks=1, @@session.sql_auto_is_null=0, @@session.unique_checks=1, @@session.autocommit=1/*!*/;
SET @@session.sql_mode=1168113696/*!*/;
SET @@session.auto_increment_increment=1, @@session.auto_increment_offset=1/*!*/;
/*!\C utf8mb4 *//*!*/;
SET @@session.character_set_client=255,@@session.collation_connection=255,@@session.collation_server=255/*!*/;
SET @@session.lc_time_names=0/*!*/;
SET @@session.collation_database=DEFAULT/*!*/;
/*!80011 SET @@session.default_collation_for_utf8mb4=255*//*!*/;
BEGIN
/*!*/;
# at 311
#260828  3:54:02 server id 1  end_log_pos 377 CRC32 0x05292b36  Table_map: `db1`.`ruoyi_user` mapped to number 115
# has_generated_invisible_primary_key=0
# at 377
#260828  3:54:02 server id 1  end_log_pos 458 CRC32 0xb93b0ef3  Write_rows: table id 115 flags: STMT_END_F

BINLOG '
WgaRahMBAAAAQgAAAHkBAAAAAHMAAAAAAAEAA2RiMQAKcnVveWlfdXNlcgADAw8PBMgAUAAGAQEA
AgP8/wA2KykF
WgaRah4BAAAAUQAAAMoBAAAAAHMAAAAAAAEAAgAD/wAEAAAABGxpc2kLMTM2MDAxMzYwMDAABQAA
AAZ3YW5nd3ULMTM1MDAxMzUwMDDzDju5
'/*!*/;
### INSERT INTO `db1`.`ruoyi_user`
### SET
###   @1=4
###   @2='lisi'
###   @3='13600136000'
### INSERT INTO `db1`.`ruoyi_user`
### SET
###   @1=5
###   @2='wangwu'
###   @3='13500135000'
# at 458
#260828  3:54:02 server id 1  end_log_pos 489 CRC32 0xd2cefcfd  Xid = 151
COMMIT/*!*/;
# at 489
#260828  3:54:12 server id 1  end_log_pos 568 CRC32 0x3c856ef5  Anonymous_GTID  last_committed=1        sequence_number=2   rbr_only=yes     original_committed_timestamp=1787889252597578   immediate_commit_timestamp=1787889252597578     transaction_length=341
/*!50718 SET TRANSACTION ISOLATION LEVEL READ COMMITTED*//*!*/;
# original_commit_timestamp=1787889252597578 (2026-08-28 03:54:12.597578 UTC)
# immediate_commit_timestamp=1787889252597578 (2026-08-28 03:54:12.597578 UTC)
/*!80001 SET @@session.original_commit_timestamp=1787889252597578*//*!*/;
/*!80014 SET @@session.original_server_version=80411*//*!*/;
/*!80014 SET @@session.immediate_server_version=80411*//*!*/;
SET @@SESSION.GTID_NEXT= 'ANONYMOUS'/*!*/;
# at 568
#260828  3:54:12 server id 1  end_log_pos 651 CRC32 0x0df2d616  Query   thread_id=17    exec_time=0     error_code=0
SET TIMESTAMP=1787889252/*!*/;
BEGIN
/*!*/;
# at 651
#260828  3:54:12 server id 1  end_log_pos 717 CRC32 0xd8810c80  Table_map: `db1`.`ruoyi_user` mapped to number 115
# has_generated_invisible_primary_key=0
# at 717
#260828  3:54:12 server id 1  end_log_pos 799 CRC32 0xc2dcef0b  Update_rows: table id 115 flags: STMT_END_F

BINLOG '
ZAaRahMBAAAAQgAAAM0CAAAAAHMAAAAAAAEAA2RiMQAKcnVveWlfdXNlcgADAw8PBMgAUAAGAQEA
AgP8/wCADIHY
ZAaRah8BAAAAUgAAAB8DAAAAAHMAAAAAAAEAAgAD//8AAQAAAAVhZG1pbgsxMzgwMDEzODAwMAAB
AAAABWFkbWluCzEzODAwMDAwMDAwC+/cwg==
'/*!*/;
### UPDATE `db1`.`ruoyi_user`
### WHERE
###   @1=1
###   @2='admin'
###   @3='13800138000'
### SET
###   @1=1
###   @2='admin'
###   @3='13800000000'
# at 799
#260828  3:54:12 server id 1  end_log_pos 830 CRC32 0x3641a317  Xid = 152
COMMIT/*!*/;
# at 830
#260828  3:54:20 server id 1  end_log_pos 909 CRC32 0x2396d43b  Anonymous_GTID  last_committed=2        sequence_number=3   rbr_only=yes     original_committed_timestamp=1787889260604837   immediate_commit_timestamp=1787889260604837     transaction_length=330
/*!50718 SET TRANSACTION ISOLATION LEVEL READ COMMITTED*//*!*/;
# original_commit_timestamp=1787889260604837 (2026-08-28 03:54:20.604837 UTC)
# immediate_commit_timestamp=1787889260604837 (2026-08-28 03:54:20.604837 UTC)
/*!80001 SET @@session.original_commit_timestamp=1787889260604837*//*!*/;
/*!80014 SET @@session.original_server_version=80411*//*!*/;
/*!80014 SET @@session.immediate_server_version=80411*//*!*/;
SET @@SESSION.GTID_NEXT= 'ANONYMOUS'/*!*/;
# at 909
#260828  3:54:20 server id 1  end_log_pos 983 CRC32 0x651b70a6  Query   thread_id=17    exec_time=0     error_code=0
SET TIMESTAMP=1787889260/*!*/;
BEGIN
/*!*/;
# at 983
#260828  3:54:20 server id 1  end_log_pos 1049 CRC32 0x3c5591a4         Table_map: `db1`.`ruoyi_user` mapped to number 115
# has_generated_invisible_primary_key=0
# at 1049
#260828  3:54:20 server id 1  end_log_pos 1129 CRC32 0x2a0f8399         Delete_rows: table id 115 flags: STMT_END_F

BINLOG '
bAaRahMBAAAAQgAAABkEAAAAAHMAAAAAAAEAA2RiMQAKcnVveWlfdXNlcgADAw8PBMgAUAAGAQEA
AgP8/wCkkVU8
bAaRaiABAAAAUAAAAGkEAAAAAHMAAAAAAAEAAgAD/wABAAAABWFkbWluCzEzODAwMDAwMDAwAAIA
AAAEdGVzdAsxMzkwMDEzOTAwMJmDDyo=
'/*!*/;
### DELETE FROM `db1`.`ruoyi_user`
### WHERE
###   @1=1
###   @2='admin'
###   @3='13800000000'
### DELETE FROM `db1`.`ruoyi_user`
### WHERE
###   @1=2
###   @2='test'
###   @3='13900139000'
# at 1129
#260828  3:54:20 server id 1  end_log_pos 1160 CRC32 0x957d93bb         Xid = 153
COMMIT/*!*/;
# at 1160
#260828  3:54:30 server id 1  end_log_pos 1239 CRC32 0x56ce7cf9         Anonymous_GTID  last_committed=1        sequence_number=4    rbr_only=yes    original_committed_timestamp=1787889270567418   immediate_commit_timestamp=1787889270567418     transaction_length=334
/*!50718 SET TRANSACTION ISOLATION LEVEL READ COMMITTED*//*!*/;
# original_commit_timestamp=1787889270567418 (2026-08-28 03:54:30.567418 UTC)
# immediate_commit_timestamp=1787889270567418 (2026-08-28 03:54:30.567418 UTC)
/*!80001 SET @@session.original_commit_timestamp=1787889270567418*//*!*/;
/*!80014 SET @@session.original_server_version=80411*//*!*/;
/*!80014 SET @@session.immediate_server_version=80411*//*!*/;
SET @@SESSION.GTID_NEXT= 'ANONYMOUS'/*!*/;
# at 1239
#260828  3:54:30 server id 1  end_log_pos 1313 CRC32 0x74d635bb         Query   thread_id=17    exec_time=0     error_code=0
SET TIMESTAMP=1787889270/*!*/;
BEGIN
/*!*/;
# at 1313
#260828  3:54:30 server id 1  end_log_pos 1379 CRC32 0xa5b0a1d9         Table_map: `db1`.`ruoyi_user` mapped to number 115
# has_generated_invisible_primary_key=0
# at 1379
#260828  3:54:30 server id 1  end_log_pos 1463 CRC32 0xf3f153e7         Write_rows: table id 115 flags: STMT_END_F

BINLOG '
dgaRahMBAAAAQgAAAGMFAAAAAHMAAAAAAAEAA2RiMQAKcnVveWlfdXNlcgADAw8PBMgAUAAGAQEA
AgP8/wDZobCl
dgaRah4BAAAAVAAAALcFAAAAAHMAAAAAAAEAAgAD/wAGAAAAB3poYW9saXULMTM0MDAxMzQwMDAA
BwAAAAZxaWFucWkLMTMzMDAxMzMwMDDnU/Hz
'/*!*/;
### INSERT INTO `db1`.`ruoyi_user`
### SET
###   @1=6
###   @2='zhaoliu'
###   @3='13400134000'
### INSERT INTO `db1`.`ruoyi_user`
### SET
###   @1=7
###   @2='qianqi'
###   @3='13300133000'
# at 1463
#260828  3:54:30 server id 1  end_log_pos 1494 CRC32 0x6b1a989d         Xid = 154
COMMIT/*!*/;
SET @@SESSION.GTID_NEXT= 'AUTOMATIC' /* added by mysqlbinlog */ /*!*/;
DELIMITER ;
# End of log file
/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;


5. 19拷贝新增数据库binlog文件
root@MYSQL-19:~# scp root@10.0.0.13:/data/mysql/logs/binlog.000002 /data/backup/
root@10.0.0.13's password:


6. 19恢复插入、更新数据,删除不要
root@MYSQL-19:~# mysqlbinlog --start-position=311 --stop-position=568 /data/backup/binlog.000002 | mysql -uroot -pXyx@123456
mysql: [Warning] Using a password on the command line interface can be insecure.
root@MYSQL-19:~# mysqlbinlog --start-position=568 --stop-position=830 /data/backup/binlog.000002 | mysql -uroot -pXyx@123456
mysql: [Warning] Using a password on the command line interface can be insecure.
root@MYSQL-19:~# mysqlbinlog --start-position=1160 --stop-position=1494 /data/backup/binlog.000002 | mysql -uroot -pXyx@123456
mysql: [Warning] Using a password on the command line interface can be insecure.

mysql> select * from db1.ruoyi_user;
+----+----------+-------------+
| id | username | phone       |
+----+----------+-------------+
|  1 | admin    | 13800000000 |
|  2 | test     | 13900139000 |
|  3 | zhangsan | 13700137000 |
|  4 | lisi     | 13600136000 |
|  5 | wangwu   | 13500135000 |
|  6 | zhaoliu  | 13400134000 |
|  7 | qianqi   | 13300133000 |
+----+----------+-------------+
7 rows in set (0.00 sec)


7. 19导出db1数据库的ruoyi_user表

root@MYSQL-19:~# mysqldump -u root -p'Xyx@123456' -S /var/run/mysqld/mysqld.sock \
--single-transaction --triggers \
db1 ruoyi_user > /data/backup/db1_ruoyi_user_$(date +%F).sql

root@MYSQL-19:~# cat /data/backup/db1_ruoyi_user_2026-08-28.sql
-- MySQL dump 10.13  Distrib 8.4.11, for Linux (x86_64)
--
-- Host: localhost    Database: db1
-- ------------------------------------------------------
-- Server version       8.4.11

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `ruoyi_user`
--

DROP TABLE IF EXISTS `ruoyi_user`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `ruoyi_user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `phone` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `ruoyi_user`
--

LOCK TABLES `ruoyi_user` WRITE;
/*!40000 ALTER TABLE `ruoyi_user` DISABLE KEYS */;
INSERT INTO `ruoyi_user` VALUES (1,'admin','13800000000'),(2,'test','13900139000'),(3,'zhangsan','13700137000'),(4,'lisi','13600136000'),(5,'wangwu','13500135000'),(6,'zhaoliu','13400134000'),(7,'qianqi','13300133000');
/*!40000 ALTER TABLE `ruoyi_user` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2026-08-28  4:28:04


8.将19导出的表拷贝到13上并恢复
root@MYSQL-19:~# scp /data/backup/db1_ruoyi_user_2026-08-28.sql root@10.0.0.13:/root
root@10.0.0.13's password:
db1_ruoyi_user_2026-08-28.sql                                      100% 2160   743.3KB/s   00:00

root@MySQL-13:~# mysql -u root -p'Xyx@123456' -S /var/run/mysqld/mysqld.sock db1 < ./db1_ruoyi_user_2026-08-28.sql
mysql: [Warning] Using a password on the command line interface can be insecure.

Linux学习之旅之MySQL主从复制

一、认识主从复制

1、什么是主从复制

一台数据库(主库)的数据变更,自动同步到一台或多台数据库(从库)。

依靠二进制日志 binlog 实现。

2、主从复制流程图

plaintext 复制代码
                主库(Source)                        从库(Replica)
+--------------------------------+       +--------------------------------+
|                                |       |                                |
|  1.客户端执行 INSERT/UPDATE/DELETE       |                                |
|          ↓                     |     |                                |
|  2.事务提交,写入 binlog日志   |        |                                |
|          ↓                     |       |                                |
|  3.Binlog‑dump推送binlog事件 ────────→ 4.IO线程接收日志
|                                |      |          ↓
|                                |     |  5.写入本地 relay‑log(中继日志)
|                                |     |          ↓
|                                |      |  6.SQL线程读取中继日志
|                                |     |          ↓
|                                |      |  7.重放SQL,数据同步完成

3、三大线程

线程 运行在哪一端 作用
Binlog‑dump 线程 主库 (Source) 等待从库连接,把 binlog 日志推送给从库
IO 线程 从库 (Replica) 连接主库,拉取 binlog,写入本地 relay‑log 中继日志
SQL 线程 从库 (Replica) 读取中继日志,重放执行 SQL,同步数据

4、三份日志对比

日志名称 存放位置 用途
binlog(二进制日志) 主库 记录所有数据变更,复制数据源
relay‑log(中继日志) 从库 临时存放拉取过来的 binlog 数据
redo‑log(重做日志) 主库、从库 InnoDB 崩溃恢复,和主从复制无关

5、复制模式(还有其它类型)

复制模式 特点 数据丢失风险
异步复制 主库提交立刻返回,不等从库 有丢数据风险
半同步复制 主库等待至少一台从库收到日志再返回 风险很低
同步复制 多节点互相通信,强一致 几乎无风险

二、主从复制部署

环境前提

bash 复制代码
系统版本:Ubuntu 24.04.4 LTS
MySQL版本:8.4.11
主机IP:10.0.0.13(MySQL-13);10.0.0.19(MySQL-19)
root@MySQL-13:~# systemctl stop mysql.service
root@MySQL-13:~# rm -rf /data/mysql/logs/* /var/lib/mysql/*
root@MySQL-13:~# mysqld --initialize-insecure --user=mysql --datadir=/var/lib/mysql
root@MySQL-13:~# systemctl start mysql.service

root@MySQL-13:~# mysql -u root -S /var/run/mysqld/mysqld.sock

mysql> alter user root@'localhost' identified WITH caching_sha2_password by 'Xyx@123456';
Query OK, 0 rows affected (0.02 sec)

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

mysql> exit
Bye


mysql> create user repluser@'10.0.0.%' identified by 'Xyx@123';
Query OK, 0 rows affected (0.01 sec)

mysql> grant replication slave on *.* to repluser@'10.0.0.%';
Query OK, 0 rows affected (0.00 sec)

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

root@MySQL-13:~# tail /etc/mysql/mysql.conf.d/mysqld.cnf
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

[mysqld]
log_timestamps = SYSTEM
log_bin = /data/mysql/logs/binlog
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
datadir         = /var/lib/mysql
log-error       = /var/log/mysql/error.log
server-id = 13   #指定server-id


root@MYSQL-19:~# tail /etc/mysql/mysql.conf.d/mysqld.cnf
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

[mysqld]
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
datadir         = /var/lib/mysql
log-error       = /var/log/mysql/error.log
server-id = 19  #指定server-id
read-only

1、无数据主从复制

bash 复制代码
1. 主节点操作
mysql> reset binary logs and gtids;
Query OK, 0 rows affected (0.02 sec)

mysql> show binary logs;
+---------------+-----------+-----------+
| Log_name      | File_size | Encrypted |
+---------------+-----------+-----------+
| binlog.000001 |       158 | No        |
+---------------+-----------+-----------+
1 row in set (0.01 sec)

mysql> show binary log status;
+---------------+----------+--------------+------------------+-------------------+
| File          | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+---------------+----------+--------------+------------------+-------------------+
| binlog.000001 |      158 |              |                  |                   |
+---------------+----------+--------------+------------------+-------------------+
1 row in set (0.01 sec)



2. 从节点配置

mysql> CHANGE REPLICATION SOURCE TO
SOURCE_HOST='10.0.0.13',
SOURCE_USER='repluser',
SOURCE_PASSWORD='Xyx@123',
SOURCE_LOG_FILE='binlog.000001',
SOURCE_LOG_POS=158;
Query OK, 0 rows affected, 2 warnings (0.03 sec)

mysql> start replica;
Query OK, 0 rows affected (0.42 sec)

mysql> show replica status\G
*************************** 1. row ***************************
             Replica_IO_State: Waiting for source to send event
                  Source_Host: 10.0.0.13
                  Source_User: repluser
                  Source_Port: 3306
                Connect_Retry: 60
              Source_Log_File: binlog.000001
          Read_Source_Log_Pos: 158
               Relay_Log_File: MYSQL-19-relay-bin.000004
                Relay_Log_Pos: 325
        Relay_Source_Log_File: binlog.000001
           Replica_IO_Running: Yes        #yes
          Replica_SQL_Running: Yes        #yes
          ..................
        Seconds_Behind_Source: 0            #主从延时0


3. 主节点增加数据测试
mysql> create database db1;
Query OK, 1 row affected (0.02 sec)

mysql> use db1;
Database changed
mysql> CREATE TABLE `student` (
    ->     `id` int unsigned NOT NULL AUTO_INCREMENT,
    ->     `name` varchar(20) NOT NULL,
    ->     `age` tinyint unsigned DEFAULT NULL,
    ->     `gender` enum('M','F') DEFAULT 'M',
    ->     PRIMARY KEY (`id`)
    -> ) ENGINE=InnoDB;
Query OK, 0 rows affected (0.03 sec)

mysql> insert into student (name,age,gender)values('user1',10,'M'),('user2',20,'F'),('user3',30,'M');
Query OK, 3 rows affected (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> show binary log status;
+---------------+----------+--------------+------------------+-------------------+
| File          | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+---------------+----------+--------------+------------------+-------------------+
| binlog.000001 |     1051 |              |                  |                   |
+---------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)


4. 从节点查看同步情况
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| db1                |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.02 sec)

mysql> show tables from db1;
+---------------+
| Tables_in_db1 |
+---------------+
| student       |
+---------------+
1 row in set (0.02 sec)

mysql> select * from db1.student;
+----+-------+------+--------+
| id | name  | age  | gender |
+----+-------+------+--------+
|  1 | user1 |   10 | M      |
|  2 | user2 |   20 | F      |
|  3 | user3 |   30 | M      |
+----+-------+------+--------+
3 rows in set (0.00 sec)

mysql> show replica status\G
*************************** 1. row ***************************
             Replica_IO_State: Waiting for source to send event
                  Source_Host: 10.0.0.13
                  Source_User: repluser
                  Source_Port: 3306
                Connect_Retry: 60
              Source_Log_File: binlog.000001
          Read_Source_Log_Pos: 1051            #和主节点binlog文件一致
               Relay_Log_File: MYSQL-19-relay-bin.000004
                Relay_Log_Pos: 1218
        Relay_Source_Log_File: binlog.000001
           Replica_IO_Running: Yes
          Replica_SQL_Running: Yes
          ...................
               Source_SSL_Key:
        Seconds_Behind_Source: 0


5. 开启和关闭主从复制

#开启
mysql> start replica;


#关闭
mysql> STOP REPLICA;
Query OK, 0 rows affected (0.01 sec)

mysql> RESET REPLICA ALL;
Query OK, 0 rows affected (0.03 sec)

2、有数据主从复制

bash 复制代码
1. 重置从节点配置
root@MYSQL-19:~# systemctl stop mysql.service
root@MYSQL-19:~# rm -rf /data/mysql/logs/* /var/lib/mysql/*
root@MYSQL-19:~# mysqld --initialize-insecure --user=mysql --datadir=/var/lib/mysql
root@MYSQL-19:~# vim /etc/profile.d/mysql.sh
root@MYSQL-19:~# source /etc/profile.d/mysql.sh
root@MYSQL-19:~# systemctl start mysql.service

root@MYSQL-19:~# mysql -u root -S /var/run/mysqld/mysqld.sock

mysql> alter user root@'localhost' identified WITH caching_sha2_password by 'Xyx@123456';
Query OK, 0 rows affected (0.02 sec)


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

mysql> reset binary logs and gtids;
Query OK, 0 rows affected (0.01 sec)


mysql> show replicas;
Empty set (0.01 sec)

mysql> show binary log status;
+---------------+----------+--------------+------------------+-------------------+
| File          | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+---------------+----------+--------------+------------------+-------------------+
| binlog.000001 |      158 |              |                  |                   |
+---------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)


2. 主节点binlog重置
mysql> reset binary logs and gtids;
Query OK, 0 rows affected (0.02 sec)

mysql> show replicas;
Empty set (0.00 sec)

mysql> show binary log status;
+---------------+----------+--------------+------------------+-------------------+
| File          | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+---------------+----------+--------------+------------------+-------------------+
| binlog.000001 |      158 |              |                  |                   |
+---------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)



3. 主节点mysqldump备份
root@MySQL-13:~# mysqldump -u root -pXyx@123456 -A -F --source-data=1 --single-transaction >all.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.
root@MySQL-13:~# ll
-rw-r--r--  1 root root 1207947 Aug 28 09:22 all.sql

root@MySQL-13:~# scp all.sql root@10.0.0.19:/root
The authenticity of host '10.0.0.19 (10.0.0.19)' can't be established.
ED25519 key fingerprint is SHA256:qfxGIdAzjwhotvmLYQbmSuHI11uN+3FXYzu/UNvbqUo.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.0.0.19' (ED25519) to the list of known hosts.
root@10.0.0.19's password:
all.sql                                                                                    100% 1180KB  10.8MB/s   00:00
root@MySQL-13:~#


4. 从节点mysqldump恢复


root@MYSQL-19:~# ls
all.sql  install_mysql84_ubuntu24.sh
root@MYSQL-19:~# vim all.sql

-- Position to start replication or point-in-time recovery from
--

CHANGE REPLICATION SOURCE TO
SOURCE_HOST='10.0.0.13',
SOURCE_USER='repluser',
SOURCE_PASSWORD='Xyx@123',
SOURCE_PORT=3306,
SOURCE_SSL=1,
SOURCE_LOG_FILE='binlog.000002', SOURCE_LOG_POS=158;

mysql> set sql_log_bin = 0;
Query OK, 0 rows affected (0.00 sec)

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

mysql> start replica;
Query OK, 0 rows affected (0.06 sec)

mysql> show replica status\G
*************************** 1. row ***************************
             Replica_IO_State: Waiting for source to send event
                  Source_Host: 10.0.0.13
                  Source_User: repluser
                  Source_Port: 3306
                Connect_Retry: 60
              Source_Log_File: binlog.000002
          Read_Source_Log_Pos: 158
               Relay_Log_File: MYSQL-19-relay-bin.000002
                Relay_Log_Pos: 325
        Relay_Source_Log_File: binlog.000002
           Replica_IO_Running: Yes
          Replica_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_Source_Log_Pos: 158
              Relay_Log_Space: 539
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Source_SSL_Allowed: Yes
           Source_SSL_CA_File:
           Source_SSL_CA_Path:
              Source_SSL_Cert:
            Source_SSL_Cipher:
               Source_SSL_Key:
        Seconds_Behind_Source: 0
Source_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Source_Server_Id: 13
                  Source_UUID: c5e043aa-a2b8-11f1-9a03-000c29ff0ffd
             Source_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
    Replica_SQL_Running_State: Replica has read all relay log; waiting for more updates
           Source_Retry_Count: 10
                  Source_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Source_SSL_Crl:
           Source_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set:
                Auto_Position: 0
         Replicate_Rewrite_DB:
                 Channel_Name:
           Source_TLS_Version:
       Source_public_key_path:
        Get_Source_public_key: 0
            Network_Namespace:
1 row in set (0.00 sec)

mysql> use db1;
Database changed
mysql> select * from student;
+----+-------+------+--------+
| id | name  | age  | gender |
+----+-------+------+--------+
|  1 | user1 |   10 | M      |
|  2 | user2 |   20 | F      |
|  3 | user3 |   30 | M      |
+----+-------+------+--------+
3 rows in set (0.01 sec)


5. 13主节点新增数据
mysql> insert into student (name,age,gender)values('user4',40,'M');
Query OK, 1 row affected (0.01 sec)



6.从19节点查询同步情况

mysql> select * from student;
+----+-------+------+--------+
| id | name  | age  | gender |
+----+-------+------+--------+
|  1 | user1 |   10 | M      |
|  2 | user2 |   20 | F      |
|  3 | user3 |   30 | M      |
|  4 | user4 |   40 | M      |
+----+-------+------+--------+
4 rows in set (0.00 sec)

Linux学习之旅之MySQL GTID复制

一、GTID基础认知

1、什么是GTID

MySQL 的 GTID(Global Transaction Identifier,全局事务标识符)是一种用于标识数据库事务的全局唯一编号,它在主从复制环境中非常有用,能够简化复制配置和故障转移过程。

GTID (Global Transaction ID,全局事务 ID),是赋予每一个提交事务的全局唯一编号。

2、优势对比表

对比维度 传统(binlog+position)复制 GTID 复制
复制起点定位 需要手动指定 binlog 文件名 + 偏移量 position 使用 AUTO_POSITION=1,自动协商同步起点,无需日志点位
主从故障切换 人工查找同步点位,操作繁琐,容易出错 自动识别已执行事务,切换简单快捷
重复事务防护 无自动判断,切换失误容易造成重复执行 SQL 执行前校验gtid_executed,自动跳过已执行事务,防重复
跳过报错事务 sql_slave_skip_counter,跳过下一条事务,盲跳、风险高 精准指定 GTID 跳过单个出错事务,安全可控
高可用适配 点位管理复杂,自动化切换脚本开发难度大 天然适配 MHA、Orchestrator、MGR 等高可用方案,易于自动化选主
级联复制 (A‑>B‑>C) 事务点位会发生变化,排查困难 GTID 全局透传,同一个事务编号全程不变
数据同步校验 很难快速判断两边实例是否执行完相同事务 对比gtid_executed集合即可快速判断同步进度
运维复杂度 拓扑越大,点位越难管理 多从库、复杂复制拓扑管理简单清晰

二、GTID实战

1、GTID配置

bash 复制代码
1. 启动gtid复制
root@MySQL-19:~# mysql
mysql: [Warning] Using a password on the command line interface can be insecure.
mysql> stop replica;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> reset replica all;
Query OK, 0 rows affected (0.00 sec)

root@MYSQL-19:~# vim /etc/mysql/mysql.conf.d/mysqld.cnf
root@MYSQL-19:~# tail -10 /etc/mysql/mysql.conf.d/mysqld.cnf
[mysqld]
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
datadir         = /var/lib/mysql
log-error       = /var/log/mysql/error.log
server-id = 19
read-only
log_bin = /data/mysql/logs/binlog
gtid_mode = ON
enforce_gtid_consistency=ON


2. 重置库
root@MYSQL-19:~# systemctl stop mysql.service
root@MYSQL-19:~# rm -rf /var/lib/mysql/* /data/mysql/logs/*
root@MYSQL-19:~# mysqld --initialize-insecure --user=mysql --datadir=/var/lib/mysql

root@MYSQL-19:~#
root@MYSQL-19:~# systemctl start mysql.service
root@MYSQL-19:~# systemctl start mysql.service
root@MYSQL-19:~# mysql -uroot -p -e "alter user root@'localhost' identified WITH caching_sha2_password by 'Xyx@123456';flush privileges;"
mysql: [Warning] Using a password on the command line interface can be insecure.
Enter password:
root@MYSQL-19:~#



3. 重置库
root@MySQL-13:~# mysql
mysql: [Warning] Using a password on the command line interface can be insecure.
mysql> stop replica;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> reset replica all;
Query OK, 0 rows affected (0.00 sec)

root@MySQL-13:~# systemctl stop mysql.service
root@MySQL-13:~# rm -rf /var/lib/mysql/* /data/mysql/logs/*
root@MySQL-13:~# mysqld --initialize-insecure --user=mysql --datadir=/var/lib/mysql
root@MySQL-13:~# systemctl start mysql.service
root@MySQL-13:~# mysql -uroot -p -e "alter user root@'localhost' identified WITH caching_sha2_password by 'Xyx@123456';flush privileges;"
mysql: [Warning] Using a password on the command line interface can be insecure.
Enter password:
root@MySQL-13:~#

4. 启动gtid
root@MySQL-13:~# vim /etc/mysql/mysql.conf.d/mysqld.cnf

[mysqld]
log_timestamps = SYSTEM
log_bin = /data/mysql/logs/binlog
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
datadir         = /var/lib/mysql
log-error       = /var/log/mysql/error.log
server-id = 13
gtid_mode = ON
enforce_gtid_consistency=ON
root@MySQL-13:~# systemctl restart mysql.service

5. 创建用户
root@MySQL-13:~# mysql
mysql: [Warning] Using a password on the command line interface can be insecure.

mysql> reset binary logs and gtids;
Query OK, 0 rows affected (0.02 sec)

mysql> show binary log status;
+---------------+----------+--------------+------------------+-------------------+
| File          | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+---------------+----------+--------------+------------------+-------------------+
| binlog.000001 |      158 |              |                  |                   |
+---------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

mysql> create user repluser@'10.0.0.%' identified by 'Xyx@123';
Query OK, 0 rows affected (0.02 sec)

mysql> grant replication slave on *.* to repluser@'10.0.0.%';
Query OK, 0 rows affected (0.01 sec)

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

mysql> show binary log status;
+---------------+----------+--------------+------------------+------------------------------------------+
| File          | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set                        |
+---------------+----------+--------------+------------------+------------------------------------------+
| binlog.000001 |      881 |              |                  | eb1cc4c3-aa57-11f1-8938-000c29ff0ffd:1-3 |
+---------------+----------+--------------+------------------+------------------------------------------+
1 row in set (0.00 sec)

mysql> show replica status\G
Empty set (0.00 sec)

mysql> show replicas;
+-----------+------+------+-----------+--------------------------------------+
| Server_Id | Host | Port | Source_Id | Replica_UUID                         |
+-----------+------+------+-----------+--------------------------------------+
|        19 |      | 3306 |        13 | 1cd64a10-aa55-11f1-aaff-000c293e140b |
+-----------+------+------+-----------+--------------------------------------+
1 row in set (0.00 sec)

mysql> create database db1;
Query OK, 1 row affected (0.01 sec)

mysql> use db1;
Database changed
mysql> CREATE TABLE `stu` (
    ->     `id` int unsigned NOT NULL AUTO_INCREMENT,
    ->     `name` varchar(20) NOT NULL,
    ->     PRIMARY KEY (`id`)
    -> ) ENGINE=InnoDB;
Query OK, 0 rows affected (0.04 sec)

mysql> insert into stu(name)values('user1');
Query OK, 1 row affected (0.02 sec)

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

mysql> show tables from db1;
+---------------+
| Tables_in_db1 |
+---------------+
| stu           |
+---------------+
1 row in set (0.00 sec)

mysql> select * from db1.stu;
+----+-------+
| id | name  |
+----+-------+
|  1 | user1 |
+----+-------+
1 row in set (0.00 sec)

mysql>



6. 连接主库
root@MYSQL-19:~# mysql
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.


mysql> CHANGE REPLICATION SOURCE TO
    -> SOURCE_HOST='10.0.0.13',
    -> SOURCE_USER='repluser',
    -> SOURCE_PASSWORD='Xyx@123',
    -> SOURCE_PORT=3306,
    -> SOURCE_SSL=1,
    -> SOURCE_AUTO_POSITION=1;
Query OK, 0 rows affected, 2 warnings (0.04 sec)
mysql> start replica;
Query OK, 0 rows affected (0.07 sec)


mysql> show replica status\G
*************************** 1. row ***************************
             Replica_IO_State: Waiting for source to send event
                  Source_Host: 10.0.0.13
                  Source_User: repluser
                  Source_Port: 3306
                Connect_Retry: 60
              Source_Log_File: binlog.000001
          Read_Source_Log_Pos: 1653
               Relay_Log_File: MYSQL-19-relay-bin.000002
                Relay_Log_Pos: 1864
        Relay_Source_Log_File: binlog.000001
           Replica_IO_Running: Yes
          Replica_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_Source_Log_Pos: 1653
              Relay_Log_Space: 2078
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Source_SSL_Allowed: Yes
           Source_SSL_CA_File:
           Source_SSL_CA_Path:
              Source_SSL_Cert:
            Source_SSL_Cipher:
               Source_SSL_Key:
        Seconds_Behind_Source: 0
Source_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Source_Server_Id: 13
                  Source_UUID: eb1cc4c3-aa57-11f1-8938-000c29ff0ffd
             Source_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
    Replica_SQL_Running_State: Replica has read all relay log; waiting for more updates
           Source_Retry_Count: 10
                  Source_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Source_SSL_Crl:
           Source_SSL_Crlpath:
           Retrieved_Gtid_Set: eb1cc4c3-aa57-11f1-8938-000c29ff0ffd:1-6
            Executed_Gtid_Set: 1cd64a10-aa55-11f1-aaff-000c293e140b:1-2,
eb1cc4c3-aa57-11f1-8938-000c29ff0ffd:1-6
                Auto_Position: 1
         Replicate_Rewrite_DB:
                 Channel_Name:
           Source_TLS_Version:
       Source_public_key_path:
        Get_Source_public_key: 0
            Network_Namespace:
1 row in set (0.00 sec)

mysql> select * from db1.stu;
+----+-------+
| id | name  |
+----+-------+
|  1 | user1 |
+----+-------+
1 row in set (0.00 sec)

2、主库故障切换、主从容灾切换完整流程

环境准备

bash 复制代码
1. 更新源
root@MySQL-13:~# apt update

2. 下载java
root@MySQL-13:~#  sudo apt install openjdk-17-jdk -y
root@MySQL-13:~# java -version
openjdk version "17.0.20" 2026-07-21
OpenJDK Runtime Environment (build 17.0.20+8-1-24.04-Ubuntu)
OpenJDK 64-Bit Server VM (build 17.0.20+8-1-24.04-Ubuntu, mixed mode, sharing)

3. 修改java环境变量
root@MySQL-13:~# echo "export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64" >> ~/.bashrc
root@MySQL-13:~# source ~/.bashrc
root@MySQL-13:~# echo $JAVA_HOME
/usr/lib/jvm/java-17-openjdk-amd64

4. 下载编译工具
root@MySQL-13:~# apt install maven -y

root@MySQL-13:~# mvn -v
Apache Maven 3.8.7

5. 创建加速
root@MySQL-13:~#  mkdir -p ~/.m2
root@MySQL-13:~# cat > ~/.m2/settings.xml <<-eof
<?xml version="1.0" encoding="UTF-8"?>
<settings>
  <mirrors>
    <mirror>
      <id>aliyun</id>
      <mirrorOf>central</mirrorOf>
      <url>https://maven.aliyun.com/repository/public</url>
    </mirror>
  </mirrors>
</settings>
eof

6. 下载nodejs环境
root@MySQL-13:~#  apt install nodejs -y
root@MySQL-13:~# node -v
v18.19.1
root@MySQL-13:~# apt install npm


root@MySQL-13:~# npm -v
9.2.0
root@MySQL-13:~# npm config set registry https://registry.npmmirror.com
root@MySQL-13:~#  npm config get registry
https://registry.npmmirror.com/

7. 安装nginx
root@MySQL-13:~# apt install nginx -y
root@MySQL-13:~# systemctl enable --now nginx
Synchronizing state of nginx.service with SysV service script with /usr/lib/systemd/systemd-sysv-install.
Executing: /usr/lib/systemd/systemd-sysv-install enable nginx
#删除默认监听
root@MySQL-13:~# rm -rf /etc/nginx/sites-enabled/default


8. 安装redis缓存
root@MySQL-13:~#  apt install redis-server -y

root@MySQL-13:~#  systemctl enable --now redis-server
Synchronizing state of redis-server.service with SysV service script with /usr/lib/systemd/systemd-sysv-install.
Executing: /usr/lib/systemd/systemd-sysv-install enable redis-server
#修改缓存配置
root@MySQL-13:~# sudo sed -i 's/bind 127.0.0.1/bind 10.0.0.13/' /etc/redis/redis.conf
root@MySQL-13:~# sed -i '/^requirepass /d' /etc/redis/redis.conf
root@MySQL-13:~#  sed -i '/# requirepass/a\requirepass "Redis@2026"' /etc/redis/redis.conf
root@MySQL-13:~# sed -i 's/^protected-mode .*/protected-mode yes/' /etc/redis/redis.conf
root@MySQL-13:~#  systemctl restart redis-server
#测试
root@MySQL-13:~# redis-cli -a 'Redis@2026' -h 10.0.0.13 ping
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
PONG
#创建ruoyi用户
root@MySQL-13:~# cat > ruoyi.sql <<-eof
CREATE DATABASE ry_vue DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'ruoyi'@'%' IDENTIFIED BY 'Ruoyi@123';
GRANT ALL ON ry_vue.* TO 'ruoyi'@'%';
FLUSH PRIVILEGES;
eof
#导入mysql
root@MySQL-13:~# mysql < ruoyi.sql
mysql: [Warning] Using a password on the command line interface can be insecure.
root@MySQL-13:~# mysql -uruoyi -p'Ruoyi@123' -h10.0.0.13 -e "show databases;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| performance_schema |
| ry_vue             |
+--------------------+

9. 安装git工具
root@MySQL-13:~# apt install git -y

#克隆若依二进制包
root@MySQL-13:~# git clone https://gitee.com/y_project/RuoYi-Vue.git
root@MySQL-13:~# ls
RuoYi-Vue
root@MySQL-13:~# cd RuoYi-Vue/
root@MySQL-13:~/RuoYi-Vue# ls
bin  LICENSE  README.md    ruoyi-common     ruoyi-generator  ruoyi-system  ry.sh
doc  pom.xml  ruoyi-admin  ruoyi-framework  ruoyi-quartz     ry.bat        sql
root@MySQL-13:~/RuoYi-Vue# cd sql/
root@MySQL-13:~/RuoYi-Vue/sql# ls
quartz.sql  ry_20260417.sql
#将若依数据导入mysql库
root@MySQL-13:~/RuoYi-Vue/sql# mysql -uruoyi -p'Ruoyi@123' -h10.0.0.13 ry_vue < ry_20260417.sql
mysql: [Warning] Using a password on the command line interface can be insecure.
root@MySQL-13:~/RuoYi-Vue/sql# mysql -uruoyi -p'Ruoyi@123' -h10.0.0.13 ry_vue < quartz.sql
mysql: [Warning] Using a password on the command line interface can be insecure.
root@MySQL-13:~/RuoYi-Vue/sql# mysql -uruoyi -p'Ruoyi@123' -h10.0.0.13 -e "show databases;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| performance_schema |
| ry_vue             |
+--------------------+

10. 修改若依配置文件
root@MySQL-13:~/RuoYi-Vue/sql# cd ../
root@MySQL-13:~/RuoYi-Vue# vim ruoyi-admin/src/main/resources/application-druid.yml
root@MySQL-13:~/RuoYi-Vue# vim ruoyi-admin/src/main/resources/application.yml
# 主库数据源
            master:
                url: jdbc:mysql://10.0.0.13:3306/ry_vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8
                username: ruoyi
                password: Ruoyi@123
root@MySQL-13:~/RuoYi-Vue# vim ruoyi-admin/src/main/resources/application.yml
data:
    # redis 配置
    redis:
      # 地址
      host: 10.0.0.13
      # 端口,默认为6379
      port: 6379
      # 数据库索引
      database: 0
      # 密码
      password: Redis@2026

11. 打包jar包并测试
root@MySQL-13:~/RuoYi-Vue# mvn clean package -Dmaven.test.skip=true
[INFO] Scanning for projects...
root@MySQL-13:~/RuoYi-Vue# ls ruoyi-admin/target/
uoyi-admin.jar  ruoyi-admin.jar.original

root@MySQL-13:~/RuoYi-Vue# java -jar ruoyi-admin/target/ruoyi-admin.jar
(♥◠‿◠)ノ゙  若依启动成功   ლ(´ڡ`ლ)゙
 .-------.       ____     __
 |  _ _   \      \   \   /  /
 | ( ' )  |       \  _. /  '
 |(_ o _) /        _( )_ .'
 | (_,_).' __  ___(_ o _)'
 |  |\ \  |  ||   |(_,_)'
 |  | \ `'   /|   `-'  /
 |  |  \    /  \      /
 ''-'   `'-'    `-..-'


12. 创建若依服务目录
root@MySQL-13:~/RuoYi-Vue#  mkdir -p /data/ruoyi/server
root@MySQL-13:~/RuoYi-Vue# cp ruoyi-admin/target/ruoyi-admin.jar /data/ruoyi/server/
root@MySQL-13:~/RuoYi-Vue# cd /data/ruoyi/server/

13. 创建systemd若依服务文件
root@MySQL-13:/data/ruoyi/server# cat > /etc/systemd/system/ruoyi-admin.service <<-eof
[Unit]
Description=RuoYi-Vue Backend Admin Service
After=network.target mysql.service redis-server.service
[Service]
User=root
WorkingDirectory=/data/ruoyi/server
# JDK17启动参数,内存可根据服务器配置调整
ExecStart=/usr/lib/jvm/java-17-openjdk-amd64/bin/java -Xms256m -Xmx512m -jar ruoyi-admin.jar
SuccessExitStatus=143
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
eof
root@MySQL-13:/data/ruoyi/server# systemctl daemon-reload
root@MySQL-13:/data/ruoyi/server# systemctl enable --now ruoyi-admin.service


root@MySQL-13:/data/ruoyi/server# netstat -tnlp | grep java
tcp6       0      0 :::8080                 :::*                    LISTEN      14190/java

14. 切换环境若依目录,需要前端环境
root@MySQL-13:/data/ruoyi/server# cd ~/RuoYi-Vue/
root@MySQL-13:~/RuoYi-Vue# git remote -v
origin  https://gitee.com/y_project/RuoYi-Vue.git (fetch)
origin  https://gitee.com/y_project/RuoYi-Vue.git (push)

root@MySQL-13:~/RuoYi-Vue# git checkout v3.9.2
M       ruoyi-admin/src/main/resources/application-druid.yml
M       ruoyi-admin/src/main/resources/application.yml
Note: switching to 'v3.9.2'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

HEAD is now at 0e2d75c2 若依 3.9.2
root@MySQL-13:~/RuoYi-Vue# ls
ruoyi-ui
root@MySQL-13:~/RuoYi-Vue# cd ruoyi-ui/

16. 安装前端依赖并打包
root@MySQL-13:~/RuoYi-Vue/ruoyi-ui# npm install
root@MySQL-13:~/RuoYi-Vue/ruoyi-ui# npm run build:prod


root@MySQL-13:~/RuoYi-Vue/ruoyi-ui# ls dist/
favicon.ico  html  index.html  index.html.gz  robots.txt  static  styles

#创建前端运行环境
root@MySQL-13:~/RuoYi-Vue/ruoyi-ui# mkdir /data/ruoyi/web/
root@MySQL-13:~/RuoYi-Vue/ruoyi-ui#  cp -r dist /data/ruoyi/web/
root@MySQL-13:~/RuoYi-Vue/ruoyi-ui#  cat .env.production
# 页面标题
VUE_APP_TITLE = 若依管理系统

# 生产环境配置
ENV = 'production'

# 若依管理系统/生产环境
VUE_APP_BASE_API = '/prod-api'

16. 创建若依虚拟主机
root@MySQL-13:~/RuoYi-Vue/ruoyi-ui#  vim /etc/nginx/conf.d/ruoyi.conf
root@MySQL-13:~/RuoYi-Vue/ruoyi-ui# cat /etc/nginx/conf.d/ruoyi.conf
server {
    listen 80;
    server_name ruoyi.magedu.com;
    # 前端静态资源根目录
    root /data/ruoyi/web/dist;
    index index.html;

    # 解决Vue History模式刷新页面404问题
    location / {
        try_files $uri $uri/ /index.html;
    }

    # 接口请求转发至后端8080端口,适配前端 /prod-api 接口前缀
    location ^~ /prod-api/ {
        proxy_pass http://127.0.0.1:8080/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # 本地文件上传访问路由
    location /profile/ {
        proxy_pass http://127.0.0.1:8080/profile/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    # 静态资源缓存优化
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        expires 1d;
        add_header Cache-Control "public";
    }
}
root@MySQL-13:~/RuoYi-Vue/ruoyi-ui# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
root@MySQL-13:~/RuoYi-Vue/ruoyi-ui# systemctl reload nginx.service

#浏览器登录:账户admin,密码admin123
http://10.0.0.13/
#浏览器登录后台监控:账户ruoyi,密码123456
http://10.0.0.13:8080/druid

Linux学习之旅之MySQL中间件部署

一、中间件基础

1、中间件是什么

bash 复制代码
中间件:介于应用程序和底层系统 / 数据库之间的一类软件,不直接处理业务逻辑,专门负责通信、调度、转发、连接管理、事务协调,为上层业务应用屏蔽底层细节。

位置:业务应用 ←→【中间件】←→ 数据库/存储

常见大类中间件:
数据库中间件:Sharding‑Sphere、MyCat、ProxySQL
消息中间件:RocketMQ、RabbitMQ、Kafka
缓存中间件:Redis
WEB 中间件:Nginx、Tomcat
事务中间件:Seata

2、中间件再MySQL环境作用

bash 复制代码
1、读写分离(最常用)

自动区分 SQL:
SELECT 查询语句 → 转发给从库,分担读压力
INSERT / UPDATE / DELETE / DDL写语句 → 转发给主库
应用层不用手动写代码区分主从地址;只连接中间件一个地址即可。
原生 MySQL 主从复制本身没有读写分离能力,复制只是数据同步,读写分离靠中间件或者应用代码实现。

2、分库分表

单表数据量巨大(千万、亿级):把一张大表,拆成多张表分散到多个 MySQL 实例。
分表:同一库内拆多张表 user_0,user_1
分库:拆分到不同数据库实例
中间件接管 SQL 路由,应用依旧像访问一张表一样,中间件自动路由到对应分片节点。

3、连接池 & 连接管理

应用大量短连接频繁创建销毁,压垮 MySQL。
中间件统一维护长连接池,复用后端 MySQL 连接,降低 MySQL 连接数压力。

4、SQL 过滤、拦截、审计

拦截危险 SQL:例如禁止 drop table、全表 delete 不带 where
SQL 日志审计,记录所有 SQL
SQL 限流,防止慢 SQL 打垮数据库

5、主从故障切换、高可用

配合 GTID 主从复制:
主库宕机,中间件自动识别,把写流量切到新晋升的主库,应用不用改 IP 地址。

6、多实例统一访问入口

后端几十套 MySQL 主从集群,应用只对接中间件统一 IP 端口,屏蔽后端多实例复杂拓扑。

二、ProxySQL 数据库代理中间件完整部署

1、 ProxySQL介绍

bash 复制代码
ProxySQL 是一款开源高性能 MySQL 代理中间件,官方网站:https://proxysql.com/ ,采用 C 语言开发,性能很高。它是独立运行的后台服务进程,部署在业务应用和 MySQL 数据库中间。

2、使用场景

bash 复制代码
1. 实现 MySQL 读写分离,写 SQL 下发主库,读 SQL 分发至多个从库;
2. 主库宕机后只修改 ProxySQL 配置,Java 代码无需改动、不用重启服务即可完成故障切换;
3. 支持 MySQL‑8.4、GTID 复制、半同步复制,适配你当前 1 主 2‑从架构;
4. 支持 SQL 限流、危险 SQL 拦截、读写权重分配、SQL 缓存、慢 SQL 统计。

3、核心能力

bash 复制代码
1、读写分离(最核心)

自动识别 SQL 类型:INSERT/UPDATE/DELETE/DCL/DDL 写语句路由到写组 hostgroup (主库);普通SELECT路由到读组 hostgroup (从库)。
特殊 SQL 处理:SELECT ... FOR UPDATE、事务内查询,强制走主库,防止读到旧数据。
规则高度灵活:支持正则、注释、schema、端口自定义路由规则,不修改业务代码实现读写分离。
hostgroup 主机组概念:ProxySQL 核心抽象,0 号写组,1 号读组;不同组存放不同 MySQL 节点。

2、读请求负载均衡

读组内多台从库流量分发,支持算法:
权重模式:性能高从库分配更高权重;
最少连接:分配给当前后端连接数最少节点;
响应时间优先;
复制延迟感知:从库延迟超过阈值,自动踢出读组,避免读取滞后脏数据。

3、高级连接池 & 连接复用(多路复用 Multiplexing)ProxySQL

前端应用成千上万短连接接入 ProxySQL;ProxySQL 向后端 MySQL 维持少量长连接,前端连接复用后端连接。
解决业务大量短连接造成 MySQL 连接数打满、连接风暴。
可限制每个后端 MySQL 最大连接数,保护数据库实例。

4、后端节点健康检测 & 故障隔离ProxySQL

定时探测后端 MySQL:连通性、read_only 状态、主从复制延迟、GTID 状态。
节点宕机 / 延迟过高:自动标记 OFFLINE,摘除流量;
故障节点恢复后,健康检查通过自动重新加入集群;
⚠️ProxySQL本身不会自动执行主从切换(不会自动把从库提升为主库);故障切换需要外部脚本 (MHA) 配合调用 ProxySQL 接口修改 hostgroup 成员。

5、SQL 查询规则引擎(Query Rules)

强大规则引擎,可以做:
SQL 重写:改写 SQL 语句;
SQL 拦截 / 黑名单:禁止危险 SQL(drop、全表 delete);
限流:限制某类 SQL 并发;
指定某些 SQL 强制走主库 / 走特定节点;
审计日志,记录匹配 SQL。

6、内置查询缓存(Query Cache)ProxySQL

代理层内存缓存 SELECT 结果集,设置 TTL 过期时间;相同查询直接返回缓存结果,不访问 MySQL。
适合字典、基础数据;写入操作不会自动失效缓存,依赖 TTL。

7、配置热加载(重要特性)

全部配置修改在线生效,无需重启 ProxySQL 进程。
流程:memory内存配置 → load xxx to runtime;持久化可以保存到磁盘 sqlite 库。
管理端口:6032(admin 管理端口);业务端口 6033(接收应用 MySQL 协议连接)。

8、监控指标统计

内置大量统计视图:
连接池状态、前后端连接统计;
SQL 执行计数、慢查询统计;
hostgroup 各节点流量统计;
缓存命中统计。
可以对接 Prometheus 做监控告警。

9、支持 GTID 复制环境适配
可以识别后端 GTID 状态,感知主从拓扑,配合 GTID 主从复制;
注意:GTID 只是 MySQL 数据同步,ProxySQL 利用 GTID 状态做健康判断,不负责同步数据。

4、admin 管理库和 runtime 运行库

数据库名 类型 读写权限 核心用途
main 内存编辑层 (memory) ✅可读可写 配置草稿区,唯一做 INSERT/UPDATE/DELETE
runtime 运行视图库 ❌只读 已经生效的运行配置,不允许 DML 修改
disk 磁盘持久 SQLite 库 ✅可读可写 持久化保存配置文件 /var/lib/proxysql/proxysql.db
stats 统计库 ❌只读 流量、连接、SQL 命中统计,故障排查
monitor 监控库 ❌只读 后端 MySQL 健康探测、主从延迟、连通性采集

三、ProxySQL部署

1、环境准备

bash 复制代码
#将三个MySQL节点恢复至GTID状态
1. 主节点13 配置
[root@Mysql-13:~#] cat >> '/etc/mysql/mysql.conf.d/mysqld.cnf' << 'EFO'
server-id = 13
gtid_mode=ON
enforce_gtid_consistency=ON
EFO

[root@Mysql-13:~#] systemctl restart mysql.service
[root@Mysql-13:~#] systemctl stop mysql.service
[root@Mysql-13:~#] rm -rf /var/lib/mysql/* /data/mysql/logs/*
[root@Mysql-13:~#] systemctl start mysql.service
[root@Mysql-13:~#] mysql

mysql> create user repluser@'10.0.0.%' identified by 'Xyx@123';
Query OK, 0 rows affected (0.05 sec)

mysql> grant replication slave on *.* to repluser@'10.0.0.%';
Query OK, 0 rows affected (0.01 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)
---------------------
GPID创建完成后,创建三个检测用户
mysql> select Host,User from mysql.user;
+-----------+------------------+
| Host      | User             |
+-----------+------------------+
| 10.0.0.%  | proxyer          |
| 10.0.0.%  | repluser         |
| 10.0.0.%  | ruoyi            |
| localhost | mysql.infoschema |
| localhost | mysql.session    |
| localhost | mysql.sys        |
| localhost | root             |
+-----------+------------------+
7 rows in set (0.04 sec)




2. 从节点16 配置
[root@Mysql-16:~#] cat >> '/etc/mysql/mysql.conf.d/mysqld.cnf' << 'EFO'
server-id = 16
gtid_mode=ON
enforce_gtid_consistency=ON
read-only
EFO

[root@Mysql-16:~#] systemctl restart mysql.service
[root@Mysql-16:~#] systemctl stop mysql.service
[root@Mysql-16:~#] rm -rf /var/lib/mysql/* /data/mysql/logs/*
[root@Mysql-16:~#] systemctl start mysql.service
mysql> CHANGE REPLICATION SOURCE TO
    -> SOURCE_HOST='10.0.0.13',
    -> SOURCE_USER='repluser',
    -> SOURCE_PASSWORD='Xyx@123',
    -> SOURCE_PORT=3306,
    -> SOURCE_SSL=1,
    -> SOURCE_AUTO_POSITION=1;
Query OK, 0 rows affected, 2 warnings (0.05 sec)

mysql> start replica;
Query OK, 0 rows affected (0.13 sec)

mysql> show replica status\G
*************************** 1. row ***************************
             Replica_IO_State: Waiting for source to send event
                  Source_Host: 10.0.0.13
                  Source_User: repluser
                  Source_Port: 3306
                Connect_Retry: 60
              Source_Log_File: binlog.000003
          Read_Source_Log_Pos: 879
               Relay_Log_File: Mysql-16-relay-bin.000002
                Relay_Log_Pos: 1090
        Relay_Source_Log_File: binlog.000003
           Replica_IO_Running: Yes
          Replica_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_Source_Log_Pos: 879
              Relay_Log_Space: 1304
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Source_SSL_Allowed: Yes
           Source_SSL_CA_File:
           Source_SSL_CA_Path:
              Source_SSL_Cert:
            Source_SSL_Cipher:
               Source_SSL_Key:
        Seconds_Behind_Source: 0
Source_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Source_Server_Id: 13
                  Source_UUID: 8a632ba7-acda-11f1-9457-000c29b758f3
             Source_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
    Replica_SQL_Running_State: Replica has read all relay log; waiting for more            updates
           Source_Retry_Count: 10
                  Source_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Source_SSL_Crl:
           Source_SSL_Crlpath:
           Retrieved_Gtid_Set: 8a632ba7-acda-11f1-9457-000c29b758f3:1-3
            Executed_Gtid_Set: 8a632ba7-acda-11f1-9457-000c29b758f3:1-3,
9ddca395-acda-11f1-9191-000c29857a6e:1-5
                Auto_Position: 1
         Replicate_Rewrite_DB:
                 Channel_Name:
           Source_TLS_Version:
       Source_public_key_path:
        Get_Source_public_key: 0
            Network_Namespace:
1 row in set (0.00 sec)


3. 从节点19 配置
[root@Mysql-19:~#]  cat >> '/etc/mysql/mysql.conf.d/mysqld.cnf' << 'EFO'
server-id = 19
gtid_mode=ON
enforce_gtid_consistency=ON
read-only
EFO
[root@Mysql-19:~#] systemctl restart mysql.service
[root@Mysql-19:~#] systemctl stop mysql.service
[root@Mysql-19:~#] rm -rf /var/lib/mysql/* /data/mysql/logs/*
[root@Mysql-19:~#] systemctl start mysql.service

mysql> CHANGE REPLICATION SOURCE TO
    -> SOURCE_HOST='10.0.0.13',
    -> SOURCE_USER='repluser',
    -> SOURCE_PASSWORD='Xyx@123',
    -> SOURCE_PORT=3306,
    -> SOURCE_SSL=1,
    -> SOURCE_AUTO_POSITION=1;
Query OK, 0 rows affected, 2 warnings (0.04 sec)

mysql> start replica;
Query OK, 0 rows affected (0.28 sec)

mysql> show replica status\G
*************************** 1. row ***************************
             Replica_IO_State: Waiting for source to send event
                  Source_Host: 10.0.0.13
                  Source_User: repluser
                  Source_Port: 3306
                Connect_Retry: 60
              Source_Log_File: binlog.000003
          Read_Source_Log_Pos: 879
               Relay_Log_File: Mysql-19-relay-bin.000002
                Relay_Log_Pos: 1090
        Relay_Source_Log_File: binlog.000003
           Replica_IO_Running: Yes
          Replica_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_Source_Log_Pos: 879
              Relay_Log_Space: 1304
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Source_SSL_Allowed: Yes
           Source_SSL_CA_File:
           Source_SSL_CA_Path:
              Source_SSL_Cert:
            Source_SSL_Cipher:
               Source_SSL_Key:
        Seconds_Behind_Source: 0
Source_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Source_Server_Id: 13
                  Source_UUID: 8a632ba7-acda-11f1-9457-000c29b758f3
             Source_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
    Replica_SQL_Running_State: Replica has read all relay log; waiting for more            updates
           Source_Retry_Count: 10
                  Source_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Source_SSL_Crl:
           Source_SSL_Crlpath:
           Retrieved_Gtid_Set: 8a632ba7-acda-11f1-9457-000c29b758f3:1-3
            Executed_Gtid_Set: 8a632ba7-acda-11f1-9457-000c29b758f3:1-3,
a093fe99-acda-11f1-b81e-000c291f2685:1-5
                Auto_Position: 1
         Replicate_Rewrite_DB:
                 Channel_Name:
           Source_TLS_Version:
       Source_public_key_path:
        Get_Source_public_key: 0
            Network_Namespace:
1 row in set (0.00 sec)

2、ProxySQL安装

bash 复制代码
[root@ProxySql-10:~#] apt update

[root@ProxySql-10:~#] wget -nv -O /etc/apt/trusted.gpg.d/proxysql-3.0.x-keyring.gpg \
'https://repo.proxysql.com/ProxySQL/proxysql-3.0.x/repo_pub_key.gpg'

[root@ProxySql-10:~#] apt install ./proxysql_3.0.9-ubuntu22_amd64.deb

[root@ProxySql-10:~#]
[root@ProxySql-10:~#] vim /etc/proxysql.cnf
[root@ProxySql-10:~#] grep -E 'admin:Xyx@123|server_version' /etc/proxysql.cnf
        admin_credentials="admin:Xyx@123"    #设置admin密码
        server_version="8.4.11"        #根据MySQL版本
[root@ProxySql-10:~#] systemctl start proxysql
[root@ProxySql-10:~#] netstat -tnlp | grep sql
tcp        0      0 0.0.0.0:6032            0.0.0.0:*               LISTEN      3035/proxysql
tcp        0      0 0.0.0.0:6033            0.0.0.0:*               LISTEN      3035/proxysql
tcp        0      0 0.0.0.0:6033            0.0.0.0:*               LISTEN      3035/proxysql
tcp        0      0 0.0.0.0:6033            0.0.0.0:*               LISTEN      3035/proxysql
tcp        0      0 0.0.0.0:6033            0.0.0.0:*               LISTEN      3035/proxysql
tcp        0      0 0.0.0.0:6132            0.0.0.0:*               LISTEN      3035/proxysql
tcp        0      0 0.0.0.0:6133            0.0.0.0:*               LISTEN      3035/proxysql
tcp        0      0 0.0.0.0:6133            0.0.0.0:*               LISTEN      3035/proxysql
tcp        0      0 0.0.0.0:6133            0.0.0.0:*               LISTEN      3035/proxysql
tcp        0      0 0.0.0.0:6133            0.0.0.0:*               LISTEN      3035/proxysql

#安装MySQL客户端
[root@ProxySql-10:~#] apt install mysql-client-core-8.0



#测试proxy SQL连接
[root@ProxySql-10:~#] mysql -uadmin -pXyx@123 -h127.0.0.1 -P6032


mysql> use main;
#插入主库节点,hostgroup_id=1为写组
mysql> INSERT INTO
mysql_servers(hostgroup_id,hostname,port,weight,max_connections,max_replication_lag,status)
    -> VALUES (1,'10.0.0.13',3306,100,1000,0,'ONLINE');
Query OK, 1 row affected (0.00 sec)

#插入从库节点,hostgroup_id=2为写组
mysql> INSERT INTO
    -> mysql_servers
    -> 
(hostgroup_id,hostname,port,weight,max_connections,max_replication_lag,status)
    -> VALUES (2,'10.0.0.16',3306,100,1000,10,'ONLINE'),(2,'10.0.0.19',3306,100,1000,10,'ONLINE');
Query OK, 2 rows affected (0.00 sec)
#保存配置
mysql> load mysql users to runtime;
Query OK, 0 rows affected (0.00 sec)

mysql> save mysql users to disk;
Query OK, 0 rows affected (0.02 sec)

mysql> SELECT hostgroup_id ,hostname ,port ,weight ,max_replication_lag ,status FROM mysql_servers ;               
+--------------+-----------+------+--------+---------------------+--------+
| hostgroup_id | hostname  | port | weight | max_replication_lag | status |
+--------------+-----------+------+--------+---------------------+--------+
| 1            | 10.0.0.13 | 3306 | 100    | 0                   | ONLINE |
| 2            | 10.0.0.16 | 3306 | 100    | 10                  | ONLINE |
| 2            | 10.0.0.19 | 3306 | 100    | 10                  | ONLINE |
+--------------+-----------+------+--------+---------------------+--------+
3 rows in set (0.00 sec)

mysql> set mysql-monitor_username='proxyer';
Query OK, 1 row affected (0.00 sec)

mysql> set mysql-monitor_password='Xyx@123';
Query OK, 1 row affected (0.00 sec)

mysql> load mysql users to runtime;
Query OK, 0 rows affected (0.00 sec)

mysql> save mysql users to disk;
Query OK, 0 rows affected (0.01 sec)

mysql> show variables like "mysql-monitor_password";
+------------------------+---------+
| Variable_name          | Value   |
+------------------------+---------+
| mysql-monitor_password | Xyx@123 |
+------------------------+---------+
1 row in set (0.00 sec)

mysql> show variables like "mysql-monitor_username ";
Empty set (0.00 sec)

mysql> show variables like "mysql-monitor_username";
+------------------------+---------+
| Variable_name          | Value   |
+------------------------+---------+
| mysql-monitor_username | proxyer |
+------------------------+---------+
1 row in set (0.00 sec)

mysql>  select * from mysql_server_connect_log ;
+-----------+------+------------------+-------------------------+---------------+
| hostname  | port | time_start_us    | connect_success_time_us | connect_error |
+-----------+------+------------------+-------------------------+---------------+
| 10.0.0.19 | 3306 | 1789698189446448 | 8239                    | NULL          |
| 10.0.0.16 | 3306 | 1789698189963716 | 13478                   | NULL          |
| 10.0.0.13 | 3306 | 1789698190480777 | 4881                    | NULL          |
+-----------+------+------------------+-------------------------+---------------+
3 rows in set (0.01 sec)

mysql> select * from mysql_server_ping_log;
+-----------+------+------------------+----------------------+------------+
| hostname  | port | time_start_us    | ping_success_time_us | ping_error |
+-----------+------+------------------+----------------------+------------+
| 10.0.0.16 | 3306 | 1789698179522969 | 3641                 | NULL       |
| 10.0.0.19 | 3306 | 1789698179524085 | 2552                 | NULL       |
| 10.0.0.13 | 3306 | 1789698179522923 | 1070                 | NULL       |
| 10.0.0.19 | 3306 | 1789698189522511 | 3382                 | NULL       |
| 10.0.0.16 | 3306 | 1789698189524237 | 1686                 | NULL       |
| 10.0.0.13 | 3306 | 1789698189524031 | 1900                 | NULL       |
| 10.0.0.13 | 3306 | 1789698199519556 | 1608                 | NULL       |
| 10.0.0.19 | 3306 | 1789698199520222 | 966                  | NULL       |
| 10.0.0.16 | 3306 | 1789698199520363 | 832                  | NULL       |
| 10.0.0.13 | 3306 | 1789698209517751 | 3016                 | NULL       |
| 10.0.0.16 | 3306 | 1789698209519779 | 1022                 | NULL       |
| 10.0.0.19 | 3306 | 1789698209518638 | 2172                 | NULL       |
| 10.0.0.13 | 3306 | 1789698219517471 | 1807                 | NULL       |
| 10.0.0.16 | 3306 | 1789698219518304 | 998                  | NULL       |
| 10.0.0.19 | 3306 | 1789698219517660 | 1648                 | NULL       |
+-----------+------+------------------+----------------------+------------+
15 rows in set (0.00 sec)



mysql> INSERT INTO mysql_users(username,password,active,max_connections)
    -> VALUES ('ruoyi','Xyx@123',1,1000);
Query OK, 1 row affected (0.00 sec)

mysql> load mysql users to runtime ;
Query OK, 0 rows affected (0.01 sec)

mysql>  save mysql users to disk;
Query OK, 0 rows affected (0.02 sec)

mysql> UPDATE mysql_users SET default_hostgroup=1 WHERE username='ruoyi ';
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT username,password,default_hostgroup,active FROM mysql_users;
+----------+----------+-------------------+--------+
| username | password | default_hostgroup | active |
+----------+----------+-------------------+--------+
| ruoyi    | Xyx@123  | 1                 | 1      |
+----------+----------+-------------------+--------+
1 row in set (0.00 sec)


mysql> load mysql users to runtime ;
Query OK, 0 rows affected (0.00 sec)

mysql> save mysql users to disk;
Query OK, 0 rows affected (0.02 sec)

mysql> exit
Bye
[root@ProxySql-10:~#] mysql -uruoyi -pXyx@123 -h10.0.0.10 -P6033 -e 'select
@@server_id ,@@read_only ,user();'
mysql: [Warning] Using a password on the command line interface can be insecure.
+-------------+-------------+-----------------+
| @@server_id | @@read_only | user()          |
+-------------+-------------+-----------------+
|          13 |           0 | ruoyi@10.0.0.10 |
+-------------+-------------+-----------------+



[root@ProxySql-10:~#] mysql -uadmin -pXyx@123 -h127.0.0.1 -P6032
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 7
Server version: 8.4.11 (ProxySQL Admin Module)

Copyright (c) 2000, 2026, 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.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use main;
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 INTO
    -> mysql_query_rules(rule_id,active,match_digest,destination_hostgroup,apply)
    -> VALUES
    -> (1,1,'^SELECT.*',2,1),
    -> (2,1,'^(INSERT|UPDATE|DELETE|CREATE|ALTER|DROP)',1,1);
Query OK, 2 rows affected (0.01 sec)

mysql>  LOAD MYSQL QUERY RULES TO RUNTIME ;
Query OK, 0 rows affected (0.01 sec)

mysql> SAVE MYSQL QUERY RULES TO DISK;
Query OK, 0 rows affected (0.03 sec)

mysql> INSERT INTO
    -> mysql_query_rules(rule_id,active,match_digest,destination_hostgroup,apply)
    -> VALUES (0 ,1 ,'^SELECT.*FOR UPDATE$',1,1);
Query OK, 1 row affected (0.01 sec)

mysql>  LOAD MYSQL QUERY RULES TO RUNTIME ;
Query OK, 0 rows affected (0.00 sec)

mysql>  SAVE MYSQL QUERY RULES TO DISK;
Query OK, 0 rows affected (0.02 sec)

mysql> SELECT rule_id,active,match_digest,destination_hostgroup,apply FROM
    -> runtime_mysql_query_rules\G
*************************** 1. row ***************************
              rule_id: 0
               active: 1
         match_digest: ^SELECT.*FOR UPDATE$
destination_hostgroup: 1
                apply: 1
*************************** 2. row ***************************
              rule_id: 1
               active: 1
         match_digest: ^SELECT.*
destination_hostgroup: 2
                apply: 1
*************************** 3. row ***************************
              rule_id: 2
               active: 1
         match_digest: ^(INSERT|UPDATE|DELETE|CREATE|ALTER|DROP)
destination_hostgroup: 1
                apply: 1
3 rows in set (0.01 sec)

mysql>  INSERT INTO mysql_query_rules
    -> (rule_id,active,match_digest,destination_hostgroup,apply)
    ->  VALUES (4 ,1,'^SHOW .*',2,1);
Query OK, 1 row affected (0.00 sec)

mysql> LOAD MYSQL QUERY RULES TO RUNTIME ;
Query OK, 0 rows affected (0.00 sec)

mysql> SAVE MYSQL QUERY RULES TO DISK;
Query OK, 0 rows affected (0.02 sec)

mysql>

mysql> USE stats;
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 digest_text,hostgroup FROM stats_mysql_query_digest WHERE digest_text
    -> LIKE 'show%';
Empty set (0.01 sec)

mysql> exit
Bye



[root@ProxySql-10:~#] mysql -uruoyi -pXyx@123 -h10.0.0.10 -P6033 -e "SELECT @@server_id;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+-------------+
| @@server_id |
+-------------+
|          16 |
+-------------+
[root@ProxySql-10:~#] mysql -uruoyi -pXyx@123 -h10.0.0.10 -P6033 -e "SELECT @@server_id;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+-------------+
| @@server_id |
+-------------+
|          16 |
+-------------+
-----------------------------
[root@Mysql-13:~#] mysql -e "set global general_log=on;"

[root@Mysql-13:~#] tail -f /var/lib/mysql/Mysql-13.log
[root@Mysql-13:~#] tail -f /var/lib/mysql/Mysql-13.log
2026-09-11T06:43:39.005128Z        45 Query     SET @slave_uuid = '9ddca395-acda-11f1-9191-000c29857a6e', @replica_uuid = '9ddca395-acda-11f1-9191-000c29857a6e'
2026-09-11T06:43:39.012007Z        45 Binlog Dump GTID  Log: '' Pos: 4 GTIDs: '8a632ba7-acda-11f1-9457-000c29b758f3:1-11,
9ddca395-acda-11f1-9191-000c29857a6e:1-5'
2026-09-11T08:46:32.292673Z        43 Quit
/usr/sbin/mysqld, Version: 8.4.11 (MySQL Community Server - GPL). started with:
Tcp port: 3306  Unix socket: /var/run/mysqld/mysqld.sock
Time                 Id Command    Argument
2026-09-18T03:19:54.975043Z        73 Quit
2026-09-18T03:20:10.082468Z        74 Connect   proxyer@10.0.0.10 on  using TCP/IP
2026-09-18T03:20:10.085096Z        74 Quit




[root@Mysql-16:~#] mysql -e "set global general_log=on ;"
tail -f /var/lib/mysql/Mysql-16.log
mysql: [Warning] Using a password on the command line interface can be insecure.
/usr/sbin/mysqld, Version: 8.4.11 (MySQL Community Server - GPL). started with:
Tcp port: 3306  Unix socket: /var/run/mysqld/mysqld.sock
Time                 Id Command    Argument
2026-09-18T03:20:52.027295Z        92 Quit


2026-09-18T03:20:59.712099Z        60 Query     SHOW REPLICA STATUS
2026-09-18T03:21:09.463336Z        93 Connect   proxyer@10.0.0.10 on  using TCP/IP
2026-09-18T03:21:09.467309Z        93 Quit
2026-09-18T03:21:09.711990Z        60 Query     SHOW REPLICA STATUS

2026-09-18T03:21:19.715353Z        60 Query     SHOW REPLICA STATUS
2026-09-18T03:21:29.713351Z        60 Query     SHOW REPLICA STATUS
2026-09-18T03:21:39.713760Z        60 Query     SHOW REPLICA STATUS
2026-09-18T03:21:49.714039Z        60 Query     SHOW REPLICA STATUS
2026-09-18T03:21:59.016858Z        94 Connect   ruoyi@10.0.0.10 on information_schema using TCP/IP
2026-09-18T03:21:59.023710Z        94 Query     SELECT @@server_id
2026-09-18T03:21:59.032320Z        94 Change user       ruoyi@10.0.0.10 on information_schema using TCP/IP
2026-09-18T03:21:59.714951Z        60 Query     SHOW REPLICA STATUS
2026-09-18T03:22:09.471056Z        95 Connect   proxyer@10.0.0.10 on  using TCP/IP
2026-09-18T03:22:09.473002Z        95 Quit
2026-09-18T03:22:09.715456Z        60 Query     SHOW REPLICA STATUS

l-10:~#] mysql -uruoyi -pXyx@123 -h10.0.0.10 -P6033 -e 'select

@@server_id ,@@read_only ,user();'

mysql: Warning Using a password on the command line interface can be insecure.

±------------±------------±----------------+

| @@server_id | @@read_only | user() |

±------------±------------±----------------+

| 13 | 0 | ruoyi@10.0.0.10 |

±------------±------------±----------------+

root@ProxySql-10:\~# mysql -uadmin -pXyx@123 -h127.0.0.1 -P6032

mysql: Warning Using a password on the command line interface can be insecure.

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 7

Server version: 8.4.11 (ProxySQL Admin Module)

Copyright © 2000, 2026, 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.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use main;

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 INTO

-> mysql_query_rules(rule_id,active,match_digest,destination_hostgroup,apply)

-> VALUES

-> (1,1,'^SELECT.*',2,1),

-> (2,1,'^(INSERT|UPDATE|DELETE|CREATE|ALTER|DROP)',1,1);

Query OK, 2 rows affected (0.01 sec)

mysql> LOAD MYSQL QUERY RULES TO RUNTIME ;

Query OK, 0 rows affected (0.01 sec)

mysql> SAVE MYSQL QUERY RULES TO DISK;

Query OK, 0 rows affected (0.03 sec)

mysql> INSERT INTO

-> mysql_query_rules(rule_id,active,match_digest,destination_hostgroup,apply)

-> VALUES (0 ,1 ,'^SELECT.*FOR UPDATE$',1,1);

Query OK, 1 row affected (0.01 sec)

mysql> LOAD MYSQL QUERY RULES TO RUNTIME ;

Query OK, 0 rows affected (0.00 sec)

mysql> SAVE MYSQL QUERY RULES TO DISK;

Query OK, 0 rows affected (0.02 sec)

mysql> SELECT rule_id,active,match_digest,destination_hostgroup,apply FROM

-> runtime_mysql_query_rules\G

*************************** 1. row ***************************

rule_id: 0

active: 1

match_digest: ^SELECT.FOR UPDATE$
destination_hostgroup: 1
apply: 1
*************************** 2. row ***************************
rule_id: 1
active: 1
match_digest: ^SELECT.

destination_hostgroup: 2

apply: 1

*************************** 3. row ***************************

rule_id: 2

active: 1

match_digest: ^(INSERT|UPDATE|DELETE|CREATE|ALTER|DROP)

destination_hostgroup: 1

apply: 1

3 rows in set (0.01 sec)

mysql> INSERT INTO mysql_query_rules

-> (rule_id,active,match_digest,destination_hostgroup,apply)

-> VALUES (4 ,1,'^SHOW .*',2,1);

Query OK, 1 row affected (0.00 sec)

mysql> LOAD MYSQL QUERY RULES TO RUNTIME ;

Query OK, 0 rows affected (0.00 sec)

mysql> SAVE MYSQL QUERY RULES TO DISK;

Query OK, 0 rows affected (0.02 sec)

mysql>

mysql> USE stats;

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 digest_text,hostgroup FROM stats_mysql_query_digest WHERE digest_text

-> LIKE 'show%';

Empty set (0.01 sec)

mysql> exit

Bye

root@ProxySql-10:\~# mysql -uruoyi -pXyx@123 -h10.0.0.10 -P6033 -e "SELECT @@server_id;"

mysql: Warning Using a password on the command line interface can be insecure.
±------------+
| @@server_id |
±------------+
| 16 |
±------------+
root@ProxySql-10:\~# mysql -uruoyi -pXyx@123 -h10.0.0.10 -P6033 -e "SELECT @@server_id;"
mysql: Warning Using a password on the command line interface can be insecure.
±------------+
| @@server_id |
±------------+
| 16 |
±------------+

root@Mysql-13:\~# mysql -e "set global general_log=on;"

root@Mysql-13:\~# tail -f /var/lib/mysql/Mysql-13.log

root@Mysql-13:\~# tail -f /var/lib/mysql/Mysql-13.log

2026-09-11T06:43:39.005128Z 45 Query SET @slave_uuid = '9ddca395-acda-11f1-9191-000c29857a6e', @replica_uuid = '9ddca395-acda-11f1-9191-000c29857a6e'

2026-09-11T06:43:39.012007Z 45 Binlog Dump GTID Log: '' Pos: 4 GTIDs: '8a632ba7-acda-11f1-9457-000c29b758f3:1-11,

9ddca395-acda-11f1-9191-000c29857a6e:1-5'

2026-09-11T08:46:32.292673Z 43 Quit

/usr/sbin/mysqld, Version: 8.4.11 (MySQL Community Server - GPL). started with:

Tcp port: 3306 Unix socket: /var/run/mysqld/mysqld.sock

Time Id Command Argument

2026-09-18T03:19:54.975043Z 73 Quit

2026-09-18T03:20:10.082468Z 74 Connect proxyer@10.0.0.10 on using TCP/IP

2026-09-18T03:20:10.085096Z 74 Quit

root@Mysql-16:\~# mysql -e "set global general_log=on ;"

tail -f /var/lib/mysql/Mysql-16.log

mysql: Warning Using a password on the command line interface can be insecure.

/usr/sbin/mysqld, Version: 8.4.11 (MySQL Community Server - GPL). started with:

Tcp port: 3306 Unix socket: /var/run/mysqld/mysqld.sock

Time Id Command Argument

2026-09-18T03:20:52.027295Z 92 Quit

2026-09-18T03:20:59.712099Z 60 Query SHOW REPLICA STATUS

2026-09-18T03:21:09.463336Z 93 Connect proxyer@10.0.0.10 on using TCP/IP

2026-09-18T03:21:09.467309Z 93 Quit

2026-09-18T03:21:09.711990Z 60 Query SHOW REPLICA STATUS

2026-09-18T03:21:19.715353Z 60 Query SHOW REPLICA STATUS

2026-09-18T03:21:29.713351Z 60 Query SHOW REPLICA STATUS

2026-09-18T03:21:39.713760Z 60 Query SHOW REPLICA STATUS

2026-09-18T03:21:49.714039Z 60 Query SHOW REPLICA STATUS

2026-09-18T03:21:59.016858Z 94 Connect ruoyi@10.0.0.10 on information_schema using TCP/IP

2026-09-18T03:21:59.023710Z 94 Query SELECT @@server_id

2026-09-18T03:21:59.032320Z 94 Change user ruoyi@10.0.0.10 on information_schema using TCP/IP

2026-09-18T03:21:59.714951Z 60 Query SHOW REPLICA STATUS

2026-09-18T03:22:09.471056Z 95 Connect proxyer@10.0.0.10 on using TCP/IP

2026-09-18T03:22:09.473002Z 95 Quit

2026-09-18T03:22:09.715456Z 60 Query SHOW REPLICA STATUS

复制代码
相关推荐
智能运维指南1 小时前
2026年ITSM系统怎么选?四款主流方案与五维评估模型
运维·itsm·嘉为蓝鲸
vortex52 小时前
常用终端模拟器全面对比:Kitty、WezTerm、Ghostty 与 Konsole
linux
知识分享小能手2 小时前
C++ 学习教程,从入门到精通,C++ 入门知识 — 完整知识点(1)
开发语言·c++·学习
我命由我123452 小时前
Git 推送报错:error: src refspec main does not match any
运维·git·gitee·github·运维开发·学习方法·版本控制
骇客野人2 小时前
测试环境MySQL迁移Vastbase(海量数据库)完整改造与落地实施方案
运维·服务器
迪康Defender2 小时前
终端安全实战:如何高效解决企业U盘泄密与管控难题
运维·网络·安全·web安全·终端安全管理
INGNIGHT3 小时前
270 · 电话号码的字母组合II(Trie)
linux·算法
zly35003 小时前
VMware Converter Standalone 物理机转化为虚拟机后源1硬盘变成了2个硬盘(2个硬盘文件)虚拟机无法启动。
linux·运维·服务器
智能运维指南3 小时前
2026 企业智能运维平台选型:私有化、信创、全链路打通该怎么权衡?
运维·嘉为蓝鲸·aiops平台·一体化运维平台