mysql进阶

mysql进阶

1. 二进制格式mysql安装

https://downloads.mysql.com/archives/get/p/23/file/mysql-5.7.37-linux-glibc2.12-x86_64.tar.gz
提前下载二进制包 传到/usr/src/下面

[root@lch ~]# cd /usr/src/
[root@lch src]# ls
debug  kernels  mysql-5.7.37-linux-glibc2.12-x86_64.tar.gz
[root@lch src]# useradd -r -M -s /sbin/nologin mysql /创建用户
[root@lch src]# id mysql
uid=994(mysql) gid=991(mysql) groups=991(mysql)
[root@lch src]# tar xf mysql-5.7.37-linux-glibc2.12-x86_64.tar.gz -C /usr/local/
[root@lch src]# cd /usr/local/
[root@lch local]# ls
bin  games    lib    libexec                              sbin   src
etc  include  lib64  mysql-5.7.37-linux-glibc2.12-x86_64  share
[root@lch local]# mv mysql-5.7.37-linux-glibc2.12-x86_64 mysql
[root@lch local]# ls
bin  etc  games  include  lib  lib64  libexec  mysql  sbin  share  src
[root@lch local]# ll
total 0
drwxr-xr-x. 2 root root   6 May 19  2020 bin
drwxr-xr-x. 2 root root   6 May 19  2020 etc
drwxr-xr-x. 2 root root   6 May 19  2020 games
drwxr-xr-x. 2 root root   6 May 19  2020 include
drwxr-xr-x. 2 root root   6 May 19  2020 lib
drwxr-xr-x. 3 root root  17 Mar  2 09:28 lib64
drwxr-xr-x. 2 root root   6 May 19  2020 libexec
drwxr-xr-x. 9 root root 129 Jun 28 13:46 mysql
drwxr-xr-x. 2 root root   6 May 19  2020 sbin
drwxr-xr-x. 5 root root  49 Mar  2 09:28 share
drwxr-xr-x. 2 root root   6 May 19  2020 src
[root@lch local]# chown -R mysql.mysql mysql //修改目录/usr/local/mysql的属主属组
[root@lch local]# ll
total 0
drwxr-xr-x. 2 root  root    6 May 19  2020 bin
drwxr-xr-x. 2 root  root    6 May 19  2020 etc
drwxr-xr-x. 2 root  root    6 May 19  2020 games
drwxr-xr-x. 2 root  root    6 May 19  2020 include
drwxr-xr-x. 2 root  root    6 May 19  2020 lib
drwxr-xr-x. 3 root  root   17 Mar  2 09:28 lib64
drwxr-xr-x. 2 root  root    6 May 19  2020 libexec
drwxr-xr-x. 9 mysql mysql 129 Jun 28 13:46 mysql
drwxr-xr-x. 2 root  root    6 May 19  2020 sbin
drwxr-xr-x. 5 root  root   49 Mar  2 09:28 share
drwxr-xr-x. 2 root  root    6 May 19  2020 src
//添加环境变量 头文件 man文件
[root@lch local]# echo 'export PATH=/usr/local/mysql/bin:$PATH' > /etc/profile.d/mysql.sh 
[root@lch local]# source /etc/profile.d/mysql.sh 
[root@lch local]# which mysql
/usr/local/mysql/bin/mysql
[root@lch mysql]# ln -s /usr/local/mysql/include /usr/include/mysql
[root@lch mysql]# vi /etc/ld.so.conf.d/mysql.conf
/usr/local/mysql/lib
[root@lch mysql]# cat /etc/ld.so.conf.d/mysql.conf 
/usr/local/mysql/lib
[root@lch mysql]# ldconfig 
[root@lch mysql]# vi /etc/man_db.conf 
MANDATORY_MANPATH                       /usr/man
MANDATORY_MANPATH                       /usr/share/man
MANDATORY_MANPATH                       /usr/local/share/man
MANDATORY_MANPATH                       /usr/local/mysql/man
//建立数据存放目录
[root@lch ~]# mkdir -p /opt/data
[root@lch ~]# chown -R mysql.mysql /opt/data/
[root@lch ~]# ll /opt/
total 0
drwxr-xr-x. 2 mysql mysql 6 Jun 28 14:00 data
[root@lch ~]# which mysqld
/usr/local/mysql/bin/mysqld
//初始化数据库
[root@lch ~]# mysqld --initialize --user mysql --datadir /opt/data
2022-06-28T06:02:27.525120Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2022-06-28T06:02:27.817249Z 0 [Warning] InnoDB: New log files created, LSN=45790
2022-06-28T06:02:27.857551Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
2022-06-28T06:02:27.926923Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: e38ccaff-f6a7-11ec-b05b-000c2935c7eb.
2022-06-28T06:02:27.927779Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
2022-06-28T06:02:28.454771Z 0 [Warning] A deprecated TLS version TLSv1 is enabled. Please use TLSv1.2 or higher.
2022-06-28T06:02:28.454799Z 0 [Warning] A deprecated TLS version TLSv1.1 is enabled. Please use TLSv1.2 or higher.
2022-06-28T06:02:28.455496Z 0 [Warning] CA certificate ca.pem is self signed.
2022-06-28T06:02:28.830803Z 1 [Note] A temporary password is generated for root@localhost: FsjNliiA2+ht
//这个命令的最后会生成一个临时密码,此处密码是 FsjNliiA2+ht
//这个密码是随机的,一定要记住这个密码,因为一会登录时会用到
[root@lch ~]# echo 'FsjNliiA2+ht' > pass
[root@lch ~]# ls
anaconda-ks.cfg  pass
//生成配置文件
[root@lch ~]# vi /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
port = 3306
pid-file = /opt/data/mysql.pid
user = mysql
skip-name-resolve
#sql-mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
//配置服务启动脚本
[root@lch mysql]# ls
1  bin  docs  include  lib  LICENSE  man  README  share  support-files
[root@lch mysql]# cd support-files/
[root@lch support-files]# ls
magic  mysqld_multi.server  mysql-log-rotate  mysql.server
[root@lch support-files]# cp mysql.server mysqld
[root@lch support-files]# ll
total 36
-rw-r--r--. 1 mysql mysql   773 Nov 30  2021 magic
-rwxr-xr-x. 1 root  root  10576 Jun 28 14:06 mysqld
-rwxr-xr-x. 1 mysql mysql  1061 Nov 30  2021 mysqld_multi.server
-rwxr-xr-x. 1 mysql mysql   894 Nov 30  2021 mysql-log-rotate
-rwxr-xr-x. 1 mysql mysql 10576 Nov 30  2021 mysql.server
[root@lch support-files]# chown -R mysql.mysql mysqld
[root@lch support-files]# ll
total 36
-rw-r--r--. 1 mysql mysql   773 Nov 30  2021 magic
-rwxr-xr-x. 1 mysql mysql 10576 Jun 28 14:06 mysqld
-rwxr-xr-x. 1 mysql mysql  1061 Nov 30  2021 mysqld_multi.server
-rwxr-xr-x. 1 mysql mysql   894 Nov 30  2021 mysql-log-rotate
-rwxr-xr-x. 1 mysql mysql 10576 Nov 30  2021 mysql.server
[root@lch support-files]# vi mysqld
basedir=/usr/local/mysql
datadir=/opt/data    //在这两行后面添加内容
[root@lch ~]# /usr/local/mysql/support-files/mysqld start
Starting MySQL.Logging to '/opt/data/lch.err'.
 SUCCESS! 
[root@lch ~]# ss -antl
State     Recv-Q    Send-Q        Local Address:Port         Peer Address:Port    Process    
LISTEN    0         128                 0.0.0.0:22                0.0.0.0:*                  
LISTEN    0         80                        *:3306                    *:*                  
LISTEN    0         128                    [::]:22                   [::]:*  
[root@lch ~]# yum -y install ncurses-compat-libs
[root@lch ~]# cat pass 
FsjNliiA2+ht
//修改密码
//使用临时密码登录
[root@lch ~]# mysql -uroot -p'FsjNliiA2+ht'
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 2
Server version: 5.7.37

Copyright (c) 2000, 2022, 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> set password = password('lch123');
Query OK, 0 rows affected, 1 warning (0.01 sec)

mysql> exit
Bye
//使用修改之后的密码登录
[root@lch ~]# mysql -uroot -p'lch123'
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 3
Server version: 5.7.37 MySQL Community Server (GPL)

Copyright (c) 2000, 2022, 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> 
//设置开机自启 关闭防火墙 selinux
[root@lch system]# systemctl disable --now firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@lch system]# setenforce 0
[root@lch system]# vi /etc/selinux/config 

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these three values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected.
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted
[root@lch system]# cp sshd.service mysqld.service 
[root@lch system]# vi mysqld.service 
[Unit]
Description=mysql server daemon
Wants=sshd-keygen.target

[Service]
Type=forking
ExecStart=/usr/local/mysql/support-files/mysqld start
ExecStop=/usr/local/mysql/support-files/mysqld stop
ExecReload=/bin/kill -HUP $MAINPID

[Install]
WantedBy=multi-user.target
[root@lch system]# systemctl daemon-reload
[root@lch system]# systemctl status mysqld
● mysqld.service - mysql server daemon
   Loaded: loaded (/usr/lib/systemd/system/mysqld.service; disabled; vendor preset: disabled)
   Active: inactive (dead)
[root@lch system]# systemctl start mysqld
[root@lch system]# systemctl status mysqld
● mysqld.service - mysql server daemon
   Loaded: loaded (/usr/lib/systemd/system/mysqld.service; disabled; vendor preset: disabled)
   Active: active (running) since Mon 2022-07-04 23:21:13 CST; 2s ago
  Process: 53383 ExecStart=/usr/local/mysql/support-files/mysqld start (code=exited, status=0/SUCCESS)
 Main PID: 53396 (mysqld_safe)
    Tasks: 28 (limit: 4744)
   Memory: 182.5M
   CGroup: /system.slice/mysqld.service
           ├─53396 /bin/sh /usr/local/mysql/bin/mysqld_safe --datadir=/opt/data --pid-file=/opt/data/>
           └─53598 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/opt/data --plugi>

Jul 04 23:21:12 lamp systemd[1]: Starting mysql server daemon...
Jul 04 23:21:13 lamp mysqld[53383]: Starting MySQL. SUCCESS!
Jul 04 23:21:13 lamp systemd[1]: Started mysql server daemon.

2. mysql配置文件

mysql的配置文件为/etc/my.cnf

配置文件查找次序:若在多个配置文件中均有设定,则最后找到的最终生效

/etc/my.cnf --> /etc/mysql/my.cnf --> --default-extra-file=/PATH/TO/CONF_FILE --> ~/.my.cnf

mysql常用配置文件参数:

参数说明
port = 3306设置监听端口
socket = /tmp/mysql.sock指定套接字文件位置
basedir = /usr/local/mysql指定MySQL的安装路径
datadir = /data/mysql指定MySQL的数据存放路径
pid-file = /data/mysql/mysql.pid指定进程ID文件存放路径
user = mysql指定MySQL以什么用户的身份提供服务
skip-name-resolve禁止MySQL对外部连接进行DNS解析使用这一选项可以消除MySQL进行DNS解析的时间。若开启该选项,则所有远程主机连接授权都要使用IP地址方式否则MySQL将无法正常处理连接请求

3. 多表联合查询

3.1 什么是多表联合查询

前面所讲的查询语句都是针对一个表的,但是在关系型数据库中,表与表之间是有联系的,所以在实际应用中,经常使用多表查询。多表查询就是同时查询两个或两个以上的表。
在 MySQL 中,多表查询主要有交叉连接、内连接、外连接、分组查询与子查询等5种。

3.2 交叉连接(CROSS JOIN)

3.2.1 笛卡尔积

交叉连接(CROSS JOIN):有两种,显式的和隐式的2种,一般用来返回连接表的笛卡尔积。
笛卡尔积(Cartesian product)是指两个集合 X 和 Y 的乘积。
例如,有 A 和 B 两个集合,它们的值如下:

A = {1,2}
B = {3,4,5}

集合 A×B 和 B×A 的结果集分别表示为:

A×B={(1,3), (1,4), (1,5), (2,3), (2,4), (2,5) };
B×A={(3,1), (3,2), (4,1), (4,2), (5,1), (5,2) };

以上 A×B 和 B×A 的结果就叫做两个集合的笛卡尔积。

并且,从以上结果我们可以看出:

  • 两个集合相乘,不满足交换率,即 A×B≠B×A。
  • A 集合和 B 集合的笛卡尔积是 A 集合的元素个数 × B 集合的元素个数。

多表查询遵循的算法就是以上提到的笛卡尔积,表与表之间的连接可以看成是在做乘法运算。在实际应用中,应避免使用笛卡尔积,因为笛卡尔积中容易存在大量的不合理数据,简单来说就是容易导致查询结果重复、混乱。

3.2.2 交叉连接

交叉连接的语法格式如下:

SELECT <字段名> FROM <表1> CROSS JOIN <表2> [WHERE子句];

SELECT <字段名> FROM <表1>, <表2> [WHERE子句];

语法说明如下:

  • 字段名:需要查询的字段名称。
  • <表1><表2>:需要交叉连接的表名。
  • WHERE 子句:用来设置交叉连接的查询条件。

注意:多个表交叉连接时,在 FROM 后连续使用 CROSS JOIN 或,即可。以上两种语法的返回结果是相同的,但是第一种语法才是官方建议的标准写法。

当连接的表之间没有关系时,我们会省略掉 WHERE 子句,这时返回结果就是两个表的笛卡尔积,返回结果数量就是两个表的数据行相乘。需要注意的是,如果每个表有 1000 行,那么返回结果的数量就有 1000×1000 = 1000000 行,数据量是非常巨大的。

交叉连接可以查询两个或两个以上的表,为了更好的理解,我们就讲解两个表的交叉连接查询。
例 1
查询学生信息表和科目信息表,并得到一个笛卡尔积。

为了方便观察学生信息表和科目表交叉连接后的运行结果,我们先分别查询出这两个表的数据,再进行交叉连接查询。
1)查询 tb_students_info 表中的数据,SQL 语句和运行结果如下:

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

mysql> use school;
Database changed
mysql> create table tb_students_info (id int primary key auto_increment,name varchar(100) not null,age tinyint,sex varchar(6),height int,course_id int) ;
Query OK, 0 rows affected (0.02 sec)

mysql> insert into tb_students_info(name,age,sex,height,course_id) values('Dany',25,'M',160,1),('Green',23,'M',158,2),('Henry',23,'F',185,1),('Jane',23,'F',162,3),('Jim',24,'F',175,2),('John',21,'F',172,4),('Lily',22,'M',165,4),('Susan',23,'M',170,5),('Thomas',22,'F',178,5),('Tom',23,'F',164,5);
Query OK, 10 rows affected (0.00 sec)
Records: 10  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM tb_students_info;
+----+--------+------+------+--------+-----------+
| id | name   | age  | sex  | height | course_id |
+----+--------+------+------+--------+-----------+
|  1 | Dany   |   25 | M    |    160 |         1 |
|  2 | Green  |   23 | M    |    158 |         2 |
|  3 | Henry  |   23 | F    |    185 |         1 |
|  4 | Jane   |   23 | F    |    162 |         3 |
|  5 | Jim    |   24 | F    |    175 |         2 |
|  6 | John   |   21 | F    |    172 |         4 |
|  7 | Lily   |   22 | M    |    165 |         4 |
|  8 | Susan  |   23 | M    |    170 |         5 |
|  9 | Thomas |   22 | F    |    178 |         5 |
| 10 | Tom    |   23 | F    |    164 |         5 |
+----+--------+------+------+--------+-----------+
10 rows in set (0.00 sec)

2)查询 tb_course 表中的数据,SQL 语句和运行结果如下:

mysql> create table tb_course (id int primary key auto_increment,course_name varchar(100) not null) ;
Query OK, 0 rows affected (0.01 sec)mysql> SELECT * FROM tb_course;
+----+-------------+
| id | course_name |
+----+-------------+
|  1 | Java        |
|  2 | MySQL       |
|  3 | Python      |
|  4 | Go          |
|  5 | C++         |
+----+-------------+
5 rows in set (0.00 sec)
mysql> desc tb_course;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| course_name | varchar(100) | NO   |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> insert into tb_course(course_name) values('Java'),('Mysql'),('Python'),('Go'),('C++');
Query OK, 5 rows affected (0.00 sec)
Records: 5  Duplicates: 0  Warnings: 0
mysql> select * from tb_course;
+----+-------------+
| id | course_name |
+----+-------------+
|  1 | Java        |
|  2 | Mysql       |
|  3 | Python      |
|  4 | Go          |
|  5 | C++         |
+----+-------------+
5 rows in set (0.00 sec)

3)使用 CROSS JOIN 查询出两张表中的笛卡尔积,SQL 语句和运行结果如下:

mysql> SELECT * FROM tb_course CROSS JOIN tb_students_info;
+----+-------------+----+--------+------+------+--------+-----------+
| id | course_name | id | name   | age  | sex  | height | course_id |
+----+-------------+----+--------+------+------+--------+-----------+
|  1 | Java        |  1 | Dany   |   25 | M    |    160 |         1 |
|  2 | Mysql       |  1 | Dany   |   25 | M    |    160 |         1 |
|  3 | Python      |  1 | Dany   |   25 | M    |    160 |         1 |
|  4 | Go          |  1 | Dany   |   25 | M    |    160 |         1 |
|  5 | C++         |  1 | Dany   |   25 | M    |    160 |         1 |
|  1 | Java        |  2 | Green  |   23 | M    |    158 |         2 |
|  2 | Mysql       |  2 | Green  |   23 | M    |    158 |         2 |
|  3 | Python      |  2 | Green  |   23 | M    |    158 |         2 |
|  4 | Go          |  2 | Green  |   23 | M    |    158 |         2 |
|  5 | C++         |  2 | Green  |   23 | M    |    158 |         2 |
|  1 | Java        |  3 | Henry  |   23 | F    |    185 |         1 |
|  2 | Mysql       |  3 | Henry  |   23 | F    |    185 |         1 |
|  3 | Python      |  3 | Henry  |   23 | F    |    185 |         1 |
|  4 | Go          |  3 | Henry  |   23 | F    |    185 |         1 |
|  5 | C++         |  3 | Henry  |   23 | F    |    185 |         1 |
|  1 | Java        |  4 | Jane   |   23 | F    |    162 |         3 |
|  2 | Mysql       |  4 | Jane   |   23 | F    |    162 |         3 |
|  3 | Python      |  4 | Jane   |   23 | F    |    162 |         3 |
|  4 | Go          |  4 | Jane   |   23 | F    |    162 |         3 |
|  5 | C++         |  4 | Jane   |   23 | F    |    162 |         3 |
|  1 | Java        |  5 | Jim    |   24 | F    |    175 |         2 |
|  2 | Mysql       |  5 | Jim    |   24 | F    |    175 |         2 |
|  3 | Python      |  5 | Jim    |   24 | F    |    175 |         2 |
|  4 | Go          |  5 | Jim    |   24 | F    |    175 |         2 |
|  5 | C++         |  5 | Jim    |   24 | F    |    175 |         2 |
|  1 | Java        |  6 | John   |   21 | F    |    172 |         4 |
|  2 | Mysql       |  6 | John   |   21 | F    |    172 |         4 |
|  3 | Python      |  6 | John   |   21 | F    |    172 |         4 |
|  4 | Go          |  6 | John   |   21 | F    |    172 |         4 |
|  5 | C++         |  6 | John   |   21 | F    |    172 |         4 |
|  1 | Java        |  7 | Lily   |   22 | M    |    165 |         4 |
|  2 | Mysql       |  7 | Lily   |   22 | M    |    165 |         4 |
|  3 | Python      |  7 | Lily   |   22 | M    |    165 |         4 |
|  4 | Go          |  7 | Lily   |   22 | M    |    165 |         4 |
|  5 | C++         |  7 | Lily   |   22 | M    |    165 |         4 |
|  1 | Java        |  8 | Susan  |   23 | M    |    170 |         5 |
|  2 | Mysql       |  8 | Susan  |   23 | M    |    170 |         5 |
|  3 | Python      |  8 | Susan  |   23 | M    |    170 |         5 |
|  4 | Go          |  8 | Susan  |   23 | M    |    170 |         5 |
|  5 | C++         |  8 | Susan  |   23 | M    |    170 |         5 |
|  1 | Java        |  9 | Thomas |   22 | F    |    178 |         5 |
|  2 | Mysql       |  9 | Thomas |   22 | F    |    178 |         5 |
|  3 | Python      |  9 | Thomas |   22 | F    |    178 |         5 |
|  4 | Go          |  9 | Thomas |   22 | F    |    178 |         5 |
|  5 | C++         |  9 | Thomas |   22 | F    |    178 |         5 |
|  1 | Java        | 10 | Tom    |   23 | F    |    164 |         5 |
|  2 | Mysql       | 10 | Tom    |   23 | F    |    164 |         5 |
|  3 | Python      | 10 | Tom    |   23 | F    |    164 |         5 |
|  4 | Go          | 10 | Tom    |   23 | F    |    164 |         5 |
|  5 | C++         | 10 | Tom    |   23 | F    |    164 |         5 |
+----+-------------+----+--------+------+------+--------+-----------+
50 rows in set (0.00 sec)

由运行结果可以看出,tb_course 和 tb_students_info 表交叉连接查询后,返回了 50 条记录。可以想象,当表中的数据较多时,得到的运行结果会非常长,而且得到的运行结果也没太大的意义。所以,通过交叉连接的方式进行多表查询的这种方法并不常用,我们应该尽量避免这种查询。

例 2
查询 tb_course 表中的 id 字段和 tb_students_info 表中的 course_id 字段相等的内容, SQL 语句和运行结果如下:

mysql> SELECT * FROM tb_course CROSS JOIN tb_students_info WHERE tb_students_info.course_id = tb_course.id;
+----+-------------+----+--------+------+------+--------+-----------+
| id | course_name | id | name   | age  | sex  | height | course_id |
+----+-------------+----+--------+------+------+--------+-----------+
|  1 | Java        |  1 | Dany   |   25 | M    |    160 |         1 |
|  2 | Mysql       |  2 | Green  |   23 | M    |    158 |         2 |
|  1 | Java        |  3 | Henry  |   23 | F    |    185 |         1 |
|  3 | Python      |  4 | Jane   |   23 | F    |    162 |         3 |
|  2 | Mysql       |  5 | Jim    |   24 | F    |    175 |         2 |
|  4 | Go          |  6 | John   |   21 | F    |    172 |         4 |
|  4 | Go          |  7 | Lily   |   22 | M    |    165 |         4 |
|  5 | C++         |  8 | Susan  |   23 | M    |    170 |         5 |
|  5 | C++         |  9 | Thomas |   22 | F    |    178 |         5 |
|  5 | C++         | 10 | Tom    |   23 | F    |    164 |         5 |
+----+-------------+----+--------+------+------+--------+-----------+
10 rows in set (0.00 sec)

如果在交叉连接时使用 WHERE 子句,MySQL 会先生成两个表的笛卡尔积,然后再选择满足 WHERE 条件的记录。因此,表的数量较多时,交叉连接会非常非常慢。一般情况下不建议使用交叉连接。

在 MySQL 中,多表查询一般使用内连接和外连接,它们的效率要高于交叉连接。

3.3 内连接

内连接(INNER JOIN)主要通过设置连接条件的方式,来移除查询结果中某些数据行的交叉连接。简单来说,就是利用条件表达式来消除交叉连接的某些数据行。

内连接使用 INNER JOIN 关键字连接两张表,并使用 ON 子句来设置连接条件。如果没有连接条件,INNER JOIN 和 CROSS JOIN 在语法上是等同的,两者可以互换。

内连接的语法格式如下:

SELECT <字段名> FROM <表1> INNER JOIN <表2> [ON子句];

语法说明如下。

  • 字段名:需要查询的字段名称。
  • <表1><表2>:需要内连接的表名。
  • INNER JOIN :内连接中可以省略 INNER 关键字,只用关键字 JOIN。
  • ON 子句:用来设置内连接的连接条件。

INNER JOIN 也可以使用 WHERE 子句指定连接条件,但是 INNER JOIN … ON 语法是官方的标准写法,而且 WHERE 子句在某些时候会影响查询的性能

多个表内连接时,在 FROM 后连续使用 INNER JOIN 或 JOIN 即可。

内连接可以查询两个或两个以上的表。为了更好的理解,暂时只讲解两个表的连接查询。
例 1
在 tb_students_info 表和 tb_course 表之间,使用内连接查询学生姓名和相对应的课程名称,SQL 语句和运行结果如下。

mysql> SELECT s.name,c.course_name FROM tb_students_info s INNER JOIN tb_course c ON s.course_id = c.id;
+--------+-------------+
| name   | course_name |
+--------+-------------+
| Dany   | Java        |
| Green  | Mysql       |
| Henry  | Java        |
| Jane   | Python      |
| Jim    | Mysql       |
| John   | Go          |
| Lily   | Go          |
| Susan  | C++         |
| Thomas | C++         |
| Tom    | C++         |
+--------+-------------+
10 rows in set (0.01 sec)

在这里的查询语句中,两个表之间的关系通过 INNER JOIN指定,连接的条件使用ON子句给出。

注意:当对多个表进行查询时,要在 SELECT 语句后面指定字段是来源于哪一张表。因此,在多表查询时,SELECT 语句后面的写法是表名.列名。另外,如果表名非常长的话,也可以给表设置别名,这样就可以直接在 SELECT 语句后面写上表的别名.列名。

3.4 外连接

内连接的查询结果都是符合连接条件的记录,而外连接会先将连接的表分为基表和参考表,再以基表为依据返回满足和不满足条件的记录。

外连接可以分为左外连接和右外连接2种,下面根据实例分别介绍左外连接和右外连接。

3.4.1 左连接

左外连接又称为左连接,使用 LEFT OUTER JOIN 关键字连接两个表,并使用 ON 子句来设置连接条件。

左连接的语法格式如下:

SELECT <字段名> FROM <表1> LEFT OUTER JOIN <表2> <ON子句>;

语法说明如下:

  • 字段名:需要查询的字段名称。
  • <表1><表2>:需要左连接的表名。
  • LEFT OUTER JOIN:左连接中可以省略 OUTER 关键字,只使用关键字 LEFT JOIN。
  • ON 子句:用来设置左连接的连接条件,不能省略。

上述语法中,"表1"为基表,"表2"为参考表。左连接查询时,可以查询出"表1"中的所有记录和"表2"中匹配连接条件的记录。如果"表1"的某行在"表2"中没有匹配行,那么在返回结果中,"表2"的字段值均为空值(NULL)。
例 1
在进行左连接查询之前,我们先查看 tb_course 和 tb_students_info 两张表中的数据。SQL 语句和运行结果如下:

mysql> insert into tb_course(course_name) values('HTML');
Query OK, 1 row affected (0.00 sec)

mysql> SELECT * FROM tb_course;
+----+-------------+
| id | course_name |
+----+-------------+
|  1 | Java        |
|  2 | Mysql       |
|  3 | Python      |
|  4 | Go          |
|  5 | C++         |
|  6 | HTML        |
+----+-------------+
6 rows in set (0.00 sec)

mysql> insert into tb_students_info(name,age,sex,height,course_id) values('LiMing',22,'M',180,7);
Query OK, 1 row affected (0.00 sec)

mysql> SELECT * FROM tb_students_info;
+----+--------+------+------+--------+-----------+
| id | name   | age  | sex  | height | course_id |
+----+--------+------+------+--------+-----------+
|  1 | Dany   |   25 | M    |    160 |         1 |
|  2 | Green  |   23 | M    |    158 |         2 |
|  3 | Henry  |   23 | F    |    185 |         1 |
|  4 | Jane   |   23 | F    |    162 |         3 |
|  5 | Jim    |   24 | F    |    175 |         2 |
|  6 | John   |   21 | F    |    172 |         4 |
|  7 | Lily   |   22 | M    |    165 |         4 |
|  8 | Susan  |   23 | M    |    170 |         5 |
|  9 | Thomas |   22 | F    |    178 |         5 |
| 10 | Tom    |   23 | F    |    164 |         5 |
| 11 | LiMing |   22 | M    |    180 |         7 |
+----+--------+------+------+--------+-----------+
11 rows in set (0.00 sec)

在 tb_students_info 表和 tb_course 表中查询所有学生姓名和相对应的课程名称,包括没有课程的学生,SQL 语句和运行结果如下:

mysql> SELECT s.name,c.course_name FROM tb_students_info s LEFT OUTER JOIN tb_course c ON s.`course_id`=c.`id`;
+--------+-------------+
| name   | course_name |
+--------+-------------+
| Dany   | Java        |
| Green  | Mysql       |
| Henry  | Java        |
| Jane   | Python      |
| Jim    | Mysql       |
| John   | Go          |
| Lily   | Go          |
| Susan  | C++         |
| Thomas | C++         |
| Tom    | C++         |
| LiMing | NULL        |
+--------+-------------+
11 rows in set (0.00 sec)

可以看到,运行结果显示了 12 条记录,name 为 LiMing 的学生目前没有课程,因为对应的 tb_course 表中没有该学生的课程信息,所以该条记录只取出了 tb_students_info 表中相应的值,而从 tb_course 表中取出的值为 NULL。

3.4.2 右连接

右外连接又称为右连接,右连接是左连接的反向连接。使用 RIGHT OUTER JOIN 关键字连接两个表,并使用 ON 子句来设置连接条件。

右连接的语法格式如下:

SELECT <字段名> FROM <表1> RIGHT OUTER JOIN <表2> <ON子句>;

语法说明如下:

  • 字段名:需要查询的字段名称。
  • <表1><表2>:需要右连接的表名。
  • RIGHT OUTER JOIN:右连接中可以省略 OUTER 关键字,只使用关键字 RIGHT JOIN。
  • ON 子句:用来设置右连接的连接条件,不能省略。

与左连接相反,右连接以"表2"为基表,"表1"为参考表。右连接查询时,可以查询出"表2"中的所有记录和"表1"中匹配连接条件的记录。如果"表2"的某行在"表1"中没有匹配行,那么在返回结果中,"表1"的字段值均为空值(NULL)。
例 2
在 tb_students_info 表和 tb_course 表中查询所有课程,包括没有学生的课程,SQL 语句和运行结果如下:

mysql> SELECT s.name,c.course_name FROM tb_students_info s RIGHT OUTER JOIN tb_course c ON s.course_id = c.id;
+--------+-------------+
| name   | course_name |
+--------+-------------+
| Dany   | Java        |
| Green  | Mysql       |
| Henry  | Java        |
| Jane   | Python      |
| Jim    | Mysql       |
| John   | Go          |
| Lily   | Go          |
| Susan  | C++         |
| Thomas | C++         |
| Tom    | C++         |
| NULL   | HTML        |
+--------+-------------+
11 rows in set (0.00 sec)

可以看到,结果显示了 11 条记录,名称为 HTML 的课程目前没有学生,因为对应的tb_students_info 表中并没有该学生的信息,所以该条记录只取出了 tb_course 表中相应的值,而从 tb_students_info 表中取出的值为 NULL。

多个表左/右连接时,在 ON 子句后连续使用 LEFT/RIGHT OUTER JOIN 或 LEFT/RIGHT JOIN 即可。

使用外连接查询时,一定要分清需要查询的结果,是需要显示左表的全部记录还是右表的全部记录,然后选择相应的左连接和右连接。

3.5 分组查询

在 MySQL 中,GROUP BY 关键字可以根据一个或多个字段对查询结果进行分组。

使用 GROUP BY 关键字的语法格式如下:

GROUP BY  <字段名>

其中,"字段名"表示需要分组的字段名称,多个字段时用逗号隔开。

3.5.1 GROUP BY单独使用

单独使用 GROUP BY 关键字时,查询结果会只显示每个分组的第一条记录。

下面根据 tb_students_info 表中的 sex 字段进行分组查询,SQL 语句和运行结果如下:

mysql> SELECT `name`,`sex` FROM tb_students_info GROUP BY sex;
+-------+------+
| name  | sex  |
+-------+------+
| Henry |  F   |
| Dany  |  M   |
+-------+------+
2 rows in set (0.01 sec)

结果中只显示了两条记录,这两条记录的 sex 字段的值分别为“女”和“男”。

3.5.2 GROUP BY 与 GROUP_CONCAT()

GROUP BY 关键字可以和 GROUP_CONCAT() 函数一起使用。GROUP_CONCAT() 函数会把每个分组的字段值都显示出来。

下面根据 tb_students_info 表中的 sex 字段进行分组查询,使用 GROUP_CONCAT() 函数将每个分组的 name 字段的值都显示出来。SQL 语句和运行结果如下:

mysql> select sex, group_concat(name) from tb_students_info group by sex;
+------+--------------------------------+
| sex  | group_concat(name)             |
+------+--------------------------------+
| F    | Henry,Jane,Jim,John,Thomas,Tom |
| M    | Dany,Green,Lily,Susan,LiMing   |
+------+--------------------------------+
2 rows in set (0.00 sec)

由结果可以看到,查询结果分为两组,sex 字段值为"女"的是一组,值为"男"的是一组,且每组的学生姓名都显示出来了。

下面根据 tb_students_info 表中的 age 和 sex 字段进行分组查询。SQL 语句和运行结果如下:

mysql> SELECT age,sex,GROUP_CONCAT(name) FROM tb_students_info GROUP BY age,sex; 
+------+------+--------------------+
| age  | sex  | GROUP_CONCAT(name) |
+------+------+--------------------+
|   21 | F    | John               |
|   22 | F    | Thomas             |
|   22 | M    | Lily,LiMing        |
|   23 | F    | Henry,Jane,Tom     |
|   23 | M    | Green,Susan        |
|   24 | F    | Jim                |
|   25 | M    | Dany               |
+------+------+--------------------+
7 rows in set (0.00 sec)

上面实例在分组过程中,先按照 age 字段进行分组,当 age 字段值相等时,再把 age 字段值相等的记录按照 sex 字段进行分组。

多个字段分组查询时,会先按照第一个字段进行分组。如果第一个字段中有相同的值,MySQL 才会按照第二个字段进行分组。如果第一个字段中的数据都是唯一的,那么 MySQL 将不再对第二个字段进行分组。

3.5.3 GROUP BY 与聚合函数

在数据统计时,GROUP BY 关键字经常和聚合函数一起使用。

聚合函数包括 COUNT(),SUM(),AVG(),MAX() 和 MIN()。其中,COUNT() 用来统计记录的条数;SUM() 用来计算字段值的总和;AVG() 用来计算字段值的平均值;MAX() 用来查询字段的最大值;MIN() 用来查询字段的最小值。

下面根据 tb_students_info 表的 sex 字段进行分组查询,使用 COUNT() 函数计算每一组的记录数。SQL 语句和运行结果如下:

mysql> SELECT sex,COUNT(sex) FROM tb_students_info GROUP BY sex;
+------+------------+
| sex  | COUNT(sex) |
+------+------------+
| F    |          6 |
| M    |          5 |
+------+------------+
2 rows in set (0.00 sec)

结果显示,sex 字段值为"女"的记录是一组,有 5 条记录;sex 字段值为"男"的记录是一组,有 5 条记录。

3.5.4 GROUP BY 与 WITH ROLLUP

WITH POLLUP 关键字用来在所有记录的最后加上一条记录,这条记录是上面所有记录的总和,即统计记录数量。

下面根据 tb_students_info 表中的 sex 字段进行分组查询,并使用 WITH ROLLUP 显示记录的总和:

mysql> SELECT sex,GROUP_CONCAT(name) FROM tb_students_info GROUP BY sex WITH ROLLUP;
+------+-------------------------------------------------------------+
| sex  | GROUP_CONCAT(name)                                          |
+------+-------------------------------------------------------------+
| F    | Henry,Jane,Jim,John,Thomas,Tom                              |
| M    | Dany,Green,Lily,Susan,LiMing                                |
| NULL | Henry,Jane,Jim,John,Thomas,Tom,Dany,Green,Lily,Susan,LiMing |
+------+-------------------------------------------------------------+
3 rows in set (0.00 sec)

查询结果显示,GROUP_CONCAT(name) 显示了每个分组的 name 字段值。同时,最后一条记录的 GROUP_CONCAT(name) 字段的值刚好是上面分组 name 字段值的总和。

3.6 子查询

子查询是 MySQL 中比较常用的查询方法,通过子查询可以实现多表查询。子查询指将一个查询语句嵌套在另一个查询语句中。子查询可以在 SELECT、UPDATE 和 DELETE 语句中使用,而且可以进行多层嵌套。在实际开发时,子查询经常出现在 WHERE 子句中。

子查询在 WHERE 中的语法格式如下:

WHERE <表达式> <操作符> (子查询)

其中,操作符可以是比较运算符和 IN、NOT IN、EXISTS、NOT EXISTS 等关键字。

1)IN | NOT IN
当表达式与子查询返回的结果集中的某个值相等时,返回 TRUE,否则返回 FALSE;若使用关键字 NOT,则返回值正好相反。

2)EXISTS | NOT EXISTS
用于判断子查询的结果集是否为空,若子查询的结果集不为空,返回 TRUE,否则返回 FALSE;若使用关键字 NOT,则返回的值正好相反。
例 1
使用子查询在 tb_students_info 表和 tb_course 表中查询学习 Java 课程的学生姓名,SQL 语句和运行结果如下:

mysql> SELECT name FROM tb_students_info WHERE course_id IN (SELECT id FROM tb_course WHERE course_name = 'Java');
+-------+
| name  |
+-------+
| Dany  |
| Henry |
+-------+
2 rows in set (0.00 sec)

结果显示,学习 Java 课程的只有 Dany 和 Henry。上述查询过程也可以分为以下 2 步执行,实现效果是相同的。
首先单独执行内查询,查询出 tb_course 表中课程为 Java 的 id,SQL 语句和运行结果如下:

mysql> SELECT id FROM tb_course WHERE course_name = 'Java';
+----+
| id |
+----+
|  1 |
+----+
1 row in set (0.00 sec)

可以看到,符合条件的 id 字段的值为 1。
然后执行外层查询,在 tb_students_info 表中查询 course_id 等于 1 的学生姓名。SQL 语句和运行结果如下:

mysql> SELECT name FROM tb_students_info WHERE course_id IN (1);
+-------+
| name  |
+-------+
| Dany  |
| Henry |
+-------+
2 rows in set (0.00 sec)

习惯上,外层的 SELECT 查询称为父查询,圆括号中嵌入的查询称为子查询(子查询必须放在圆括号内)。MySQL 在处理上例的 SELECT 语句时,执行流程为:先执行子查询,再执行父查询。
例 2
与例 1 类似,在 SELECT 语句中使用 NOT IN 关键字,查询没有学习 Java 课程的学生姓名,SQL 语句和运行结果如下:

mysql> SELECT name FROM tb_students_info WHERE course_id NOT IN (SELECT id FROM tb_course WHERE course_name = 'Java');
+--------+
| name   |
+--------+
| Green  |
| Jane   |
| Jim    |
| John   |
| Lily   |
| Susan  |
| Thomas |
| Tom    |
| LiMing |
+--------+
9 rows in set (0.00 sec)

可以看出,运行结果与上面的例子刚好相反,没有学习 Java 课程的是除了 Dany 和 Henry 之外的学生。
例 3
使用=运算符,在 tb_course 表和 tb_students_info 表中查询出所有学习 Python 课程的学生姓名,SQL 语句和运行结果如下:

mysql> SELECT name FROM tb_students_info WHERE course_id = (SELECT id FROM tb_course WHERE course_name = 'Python');
+------+
| name |
+------+
| Jane |
+------+
1 row in set (0.00 sec)

结果显示,学习 Python 课程的学生只有 Jane。
例 4
使用<>运算符,在 tb_course 表和 tb_students_info 表中查询出没有学习 Python 课程的学生姓名,SQL 语句和运行结果如下:

mysql> SELECT name FROM tb_students_info WHERE course_id <> (SELECT id FROM tb_course WHERE course_name = 'Python');
+--------+
| name   |
+--------+
| Dany   |
| Green  |
| Henry  |
| Jim    |
| John   |
| Lily   |
| Susan  |
| Thomas |
| Tom    |
| LiMing |
+--------+
10 rows in set (0.00 sec)

可以看出,运行结果与例 3 刚好相反,没有学习 Python 课程的是除了 Jane 之外的学生。
例 5
查询 tb_course 表中是否存在 id=1 的课程,如果存在,就查询出 tb_students_info 表中的记录,SQL 语句和运行结果如下:

mysql> SELECT * FROM tb_students_info WHERE EXISTS(SELECT course_name FROM tb_course WHERE id=1);
+----+--------+------+------+--------+-----------+
| id | name   | age  | sex  | height | course_id |
+----+--------+------+------+--------+-----------+
|  1 | Dany   |   25 | M    |    160 |         1 |
|  2 | Green  |   23 | M    |    158 |         2 |
|  3 | Henry  |   23 | F    |    185 |         1 |
|  4 | Jane   |   23 | F    |    162 |         3 |
|  5 | Jim    |   24 | F    |    175 |         2 |
|  6 | John   |   21 | F    |    172 |         4 |
|  7 | Lily   |   22 | M    |    165 |         4 |
|  8 | Susan  |   23 | M    |    170 |         5 |
|  9 | Thomas |   22 | F    |    178 |         5 |
| 10 | Tom    |   23 | F    |    164 |         5 |
| 11 | LiMing |   22 | M    |    180 |         7 |
+----+--------+------+------+--------+-----------+
11 rows in set (0.00 sec)

由结果可以看到,tb_course 表中存在 id=1 的记录,因此 EXISTS 表达式返回 TRUE,外层查询语句接收 TRUE 之后对表 tb_students_info 进行查询,返回所有的记录。

EXISTS 关键字可以和其它查询条件一起使用,条件表达式与 EXISTS 关键字之间用 AND 和 OR 连接。
例 6
查询 tb_course 表中是否存在 id=1 的课程,如果存在,就查询出 tb_students_info 表中 age 字段大于 24 的记录,SQL 语句和运行结果如下:

mysql> SELECT * FROM tb_students_info WHERE age>24 AND EXISTS(SELECT course_name FROM tb_course WHERE id=1);
+----+------+------+------+--------+-----------+
| id | name | age  | sex  | height | course_id |
+----+------+------+------+--------+-----------+
|  1 | Dany |   25 | M    |    160 |         1 |
+----+------+------+------+--------+-----------+
1 row in set (0.00 sec)

结果显示,从 tb_students_info 表中查询出了一条记录,这条记录的 age 字段取值为 25。内层查询语句从 tb_course 表中查询到记录,返回 TRUE。外层查询语句开始进行查询。根据查询条件,从 tb_students_info 表中查询 age 大于 24 的记录。

子查询的功能也可以通过表连接完成,但是子查询会使 SQL 语句更容易阅读和编写。

一般来说,表连接(内连接和外连接等)都可以用子查询替换,但反过来却不一定,有的子查询不能用表连接来替换。子查询比较灵活、方便、形式多样,适合作为查询的筛选条件,而表连接更适合于查看连接表的数据。

4. mysql数据库备份与恢复

4.1 数据库常用备份方案

数据库备份方案:

  • 全量备份
  • 增量备份
  • 差异备份
备份方案特点
全量备份全量备份就是指对某一个时间点上的所有数据或应用进行的一个完全拷贝。数据恢复快。备份时间长
增量备份增量备份是指在一次全备份或上一次增量备份后,以后每次的备份只需备份与前一次相比增加和者被修改的文件。这就意味着,第一次增量备份的对象是进行全备后所产生的增加和修改的文件;第二次增量备份的对象是进行第一次增量备份后所产生的增加和修改的文件,如此类推。没有重复的备份数据备份时间短恢复数据时必须按一定的顺序进行
差异备份备份上一次的完全备份后发生变化的所有文件。差异备份是指在一次全备份后到进行差异备份的这段时间内对那些增加或者修改文件的备份。在进行恢复时,我们只需对第一次全量备份和最后一次差异备份进行恢复。

4.2 mysql备份工具mysqldump

//语法:
    mysqldump [OPTIONS] database [tables ...]
    mysqldump [OPTIONS] --all-databases [OPTIONS]
    mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...]
    
//常用的OPTIONS:
    -uUSERNAME      //指定数据库用户名
    -hHOST          //指定服务器主机,请使用ip地址
    -pPASSWORD      //指定数据库用户的密码
    -P#             //指定数据库监听的端口,这里的#需用实际的端口号代替,如-P3307
 
 
 
    
//备份整个数据库(全备)
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| school             |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

mysql> use school;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+------------------+
| Tables_in_school |
+------------------+
| tb_course        |
| tb_students_info |
+------------------+
2 rows in set (0.00 sec)

[root@node1 ~]# ls
anaconda-ks.cfg
[root@node1 ~]# mysqldump -uroot -p123456 --all-databases > all-$(date +%Y%m%d%H%M%S).sql
[root@node1 ~]# ls
all-20220630204353.sql  anaconda-ks.cfg




//备份school库的tb_course表和tb_students表
[root@node1 ~]# mysqldump -uroot -p123456 school tb_course tb_students_info > school-$(date +%Y%m%d%H%M%S).sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.
[root@node1 ~]# ls
all-20220630204353.sql  school-20220630204739.sql
anaconda-ks.cfg         table-20220630205128.sql



//备份school库
[root@node1 ~]# mysqldump -uroot -p123456 --databases school > school-$(date +%Y%m%d%H%M%S).sql
[root@node1 ~]# ls
all-20220630204353.sql  anaconda-ks.cfg  school-20220630204739.sql



//模拟误删school数据库
mysql> drop database school;
Query OK, 2 rows affected (0.02 sec)

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

4.3 mysql数据恢复

//恢复school数据库
[[root@node1 ~]# ls
all-20220630204353.sql  school-20220630204739.sql
anaconda-ks.cfg         table-20220630205128.sql
[root@node1 ~]# mysql -uroot -p123456 < school-20220630204739.sql 
mysql: [Warning] Using a password on the command line interface can be insecure
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| school             |
| sys                |
+--------------------+
5 rows in set (0.00 sec)






//恢复school数据库的tb_course表和tb_students_info表
mysql> drop table tb_course;
Query OK, 0 rows affected (0.01 sec)

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

mysql> show tables;
Empty set (0.00 sec)

[root@node1 ~]# mysql -uroot -p123456 school < table-20220630205128.sql 
mysql: [Warning] Using a password on the command line interface can be insecure.

mysql> show tables;
+------------------+
| Tables_in_school |
+------------------+
| tb_course        |
| tb_students_info |
+------------------+
2 rows in set (0.00 sec)

4.4 差异备份与恢复

4.4.1. mysql差异备份

开启MySQL服务器的二进制日志功能

[root@node1 etc]# vi my.cnf 
[mysqld]
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
port = 3306
pid-file = /opt/data/mysql.pid
user = mysql
skip-name-resolve

server-id = 1  //设置服务器标识符
log-bin = mysql_bin  //开启二进制日志功能

[root@node1 ~]# systemctl restart mysqld

对数据库进行完全备份

mysql> show tables;
+------------------+
| Tables_in_school |
+------------------+
| tb_course        |
| tb_students_info |
+------------------+
2 rows in set (0.00 sec)

mysql> select * from tb_course;
+----+-------------+
| id | course_name |
+----+-------------+
|  1 | Java        |
|  2 | Mysql       |
|  3 | Python      |
|  4 | Go          |
|  5 | C++         |
|  6 | HTML        |
+----+-------------+
6 rows in set (0.01 sec)

mysql> select * from tb_students_info;
+----+--------+------+------+--------+-----------+
| id | name   | age  | sex  | height | course_id |
+----+--------+------+------+--------+-----------+
|  1 | Dany   |   25 | M    |    160 |         1 |
|  2 | Green  |   23 | M    |    158 |         2 |
|  3 | Henry  |   23 | F    |    185 |         1 |
|  4 | Jane   |   23 | F    |    162 |         3 |
|  5 | Jim    |   24 | F    |    175 |         2 |
|  6 | John   |   21 | F    |    172 |         4 |
|  7 | Lily   |   22 | M    |    165 |         4 |
|  8 | Susan  |   23 | M    |    170 |         5 |
|  9 | Thomas |   22 | F    |    178 |         5 |
| 10 | Tom    |   23 | F    |    164 |         5 |
| 11 | LiMing |   22 | M    |    180 |         7 |
+----+--------+------+------+--------+-----------+
11 rows in set (0.00 sec)

//完全备份
[root@node1 ~]# mysqldump -uroot -plch123 --single-transaction --flush-logs --master-data=2 --all-databases --delete-master-logs > all-$(date +%Y%m%d%H%M%S).sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.
[root@node1 ~]# ls
all-20220630204353.sql  anaconda-ks.cfg            table-20220630205128.sql
all-20220630211225.sql  school-20220630204739.sql



//增加新内容
mysql> create table info(id int primary key auto_increment,name varchar(100) not null);
Query OK, 0 rows affected (0.01 sec)

mysql> show tables;
+------------------+
| Tables_in_school |
+------------------+
| info             |
| tb_course        |
| tb_students_info |
+------------------+
3 rows in set (0.00 sec)

mysql> insert into info(name) values('tom'),('jerry'),('bob');
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from info;
+----+-------+
| id | name  |
+----+-------+
|  1 | tom   |
|  2 | jerry |
|  3 | bob   |
+----+-------+
3 rows in set (0.00 sec)

mysql> select * from tb_students_info;
+----+--------+------+------+--------+-----------+
| id | name   | age  | sex  | height | course_id |
+----+--------+------+------+--------+-----------+
|  1 | Dany   |   25 | M    |    160 |         1 |
|  2 | Green  |   23 | M    |    158 |         2 |
|  3 | Henry  |   23 | F    |    185 |         1 |
|  4 | Jane   |   23 | F    |    162 |         3 |
|  5 | Jim    |   24 | F    |    175 |         2 |
|  6 | John   |   21 | F    |    172 |         4 |
|  7 | Lily   |   22 | M    |    165 |         4 |
|  8 | Susan  |   23 | M    |    170 |         5 |
|  9 | Thomas |   22 | F    |    178 |         5 |
| 10 | Tom    |   23 | F    |    164 |         5 |
| 11 | LiMing |   22 | M    |    180 |         7 |
+----+--------+------+------+--------+-----------+
11 rows in set (0.00 sec)

mysql> update tb_students_info set age = 50 where id = 10;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from tb_students_info;
+----+--------+------+------+--------+-----------+
| id | name   | age  | sex  | height | course_id |
+----+--------+------+------+--------+-----------+
|  1 | Dany   |   25 | M    |    160 |         1 |
|  2 | Green  |   23 | M    |    158 |         2 |
|  3 | Henry  |   23 | F    |    185 |         1 |
|  4 | Jane   |   23 | F    |    162 |         3 |
|  5 | Jim    |   24 | F    |    175 |         2 |
|  6 | John   |   21 | F    |    172 |         4 |
|  7 | Lily   |   22 | M    |    165 |         4 |
|  8 | Susan  |   23 | M    |    170 |         5 |
|  9 | Thomas |   22 | F    |    178 |         5 |
| 10 | Tom    |   50 | F    |    164 |         5 |
| 11 | LiMing |   22 | M    |    180 |         7 |
+----+--------+------+------+--------+-----------+
11 rows in set (0.00 sec)

mysql> select * from tb_course;
+----+-------------+
| id | course_name |
+----+-------------+
|  1 | Java        |
|  2 | Mysql       |
|  3 | Python      |
|  4 | Go          |
|  5 | C++         |
|  6 | HTML        |
+----+-------------+
6 rows in set (0.00 sec)

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

mysql> select * from tb_course;
+----+-------------+
| id | course_name |
+----+-------------+
|  1 | Java        |
|  2 | Mysql       |
|  3 | Python      |
|  4 | Go          |
|  5 | C++         |
+----+-------------+
4.4.2. mysql差异备份恢复

模拟误删数据

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

mysql> drop database school;
Query OK, 3 rows affected (0.01 sec)

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


刷新创建新的二进制日志

[root@node1 data]# ll
total 122996
-rw-r-----. 1 mysql mysql    32247 Jun 30 21:05 apache.err
-rw-r-----. 1 mysql mysql       56 Jun 29 00:28 auto.cnf
-rw-------. 1 mysql mysql     1680 Jun 29 00:28 ca-key.pem
-rw-r--r--. 1 mysql mysql     1112 Jun 29 00:28 ca.pem
-rw-r--r--. 1 mysql mysql     1112 Jun 29 00:28 client-cert.pem
-rw-------. 1 mysql mysql     1676 Jun 29 00:28 client-key.pem
-rw-r-----. 1 mysql mysql      559 Jun 30 21:05 ib_buffer_pool
-rw-r-----. 1 mysql mysql 12582912 Jun 30 21:31 ibdata1
-rw-r-----. 1 mysql mysql 50331648 Jun 30 21:31 ib_logfile0
-rw-r-----. 1 mysql mysql 50331648 Jun 29 00:28 ib_logfile1
-rw-r-----. 1 mysql mysql 12582912 Jun 30 21:12 ibtmp1
drwxr-x---. 2 mysql mysql     4096 Jun 29 00:28 mysql
-rw-r-----. 1 mysql mysql     1250 Jun 30 21:31 mysql_bin.000002
-rw-r-----. 1 mysql mysql       19 Jun 30 21:12 mysql_bin.index
-rw-r-----. 1 mysql mysql        6 Jun 30 21:05 mysql.pid
-rw-r-----. 1 mysql mysql     3770 Jun 30 21:05 node1.err
drwxr-x---. 2 mysql mysql     8192 Jun 29 00:28 performance_schema
-rw-------. 1 mysql mysql     1680 Jun 29 00:28 private_key.pem
-rw-r--r--. 1 mysql mysql      452 Jun 29 00:28 public_key.pem
drwxr-x---. 2 mysql mysql      150 Jun 30 21:27 school
-rw-r--r--. 1 mysql mysql     1112 Jun 29 00:28 server-cert.pem
-rw-------. 1 mysql mysql     1676 Jun 29 00:28 server-key.pem
drwxr-x---. 2 mysql mysql     8192 Jun 29 00:28 sys
[root@node1 data]# cd
[root@node1 ~]# mysqladmin -uroot -plch123 flush-logs
mysqladmin: [Warning] Using a password on the command line interface can be insecure.
[root@node1 ~]# ll /opt/data/
total 123000
-rw-r-----. 1 mysql mysql    32247 Jun 30 21:05 apache.err
-rw-r-----. 1 mysql mysql       56 Jun 29 00:28 auto.cnf
-rw-------. 1 mysql mysql     1680 Jun 29 00:28 ca-key.pem
-rw-r--r--. 1 mysql mysql     1112 Jun 29 00:28 ca.pem
-rw-r--r--. 1 mysql mysql     1112 Jun 29 00:28 client-cert.pem
-rw-------. 1 mysql mysql     1676 Jun 29 00:28 client-key.pem
-rw-r-----. 1 mysql mysql      559 Jun 30 21:05 ib_buffer_pool
-rw-r-----. 1 mysql mysql 12582912 Jun 30 21:33 ibdata1
-rw-r-----. 1 mysql mysql 50331648 Jun 30 21:33 ib_logfile0
-rw-r-----. 1 mysql mysql 50331648 Jun 29 00:28 ib_logfile1
-rw-r-----. 1 mysql mysql 12582912 Jun 30 21:12 ibtmp1
drwxr-x---. 2 mysql mysql     4096 Jun 29 00:28 mysql
-rw-r-----. 1 mysql mysql     1460 Jun 30 21:34 mysql_bin.000002
-rw-r-----. 1 mysql mysql      154 Jun 30 21:34 mysql_bin.000003
-rw-r-----. 1 mysql mysql       38 Jun 30 21:34 mysql_bin.index
-rw-r-----. 1 mysql mysql        6 Jun 30 21:05 mysql.pid
-rw-r-----. 1 mysql mysql     3770 Jun 30 21:05 node1.err
drwxr-x---. 2 mysql mysql     8192 Jun 29 00:28 performance_schema
-rw-------. 1 mysql mysql     1680 Jun 29 00:28 private_key.pem
-rw-r--r--. 1 mysql mysql      452 Jun 29 00:28 public_key.pem
-rw-r--r--. 1 mysql mysql     1112 Jun 29 00:28 server-cert.pem
-rw-------. 1 mysql mysql     1676 Jun 29 00:28 server-key.pem
drwxr-x---. 2 mysql mysql     8192 Jun 29 00:28 sys

恢复完全备份

[root@node1 ~]# mysql -uroot -plch123 < all-20220630211225.sql
mysql: [Warning] Using a password on the command line interface can be insecure.
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| school             |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

mysql> use school;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+------------------+
| Tables_in_school |
+------------------+
| tb_course        |
| tb_students_info |
+------------------+
2 rows in set (0.00 sec)

mysql> select * from tb_course;
+----+-------------+
| id | course_name |
+----+-------------+
|  1 | Java        |
|  2 | Mysql       |
|  3 | Python      |
|  4 | Go          |
|  5 | C++         |
|  6 | HTML        |
+----+-------------+
6 rows in set (0.00 sec)

mysql> select * from tb_students_info;
+----+--------+------+------+--------+-----------+
| id | name   | age  | sex  | height | course_id |
+----+--------+------+------+--------+-----------+
|  1 | Dany   |   25 | M    |    160 |         1 |
|  2 | Green  |   23 | M    |    158 |         2 |
|  3 | Henry  |   23 | F    |    185 |         1 |
|  4 | Jane   |   23 | F    |    162 |         3 |
|  5 | Jim    |   24 | F    |    175 |         2 |
|  6 | John   |   21 | F    |    172 |         4 |
|  7 | Lily   |   22 | M    |    165 |         4 |
|  8 | Susan  |   23 | M    |    170 |         5 |
|  9 | Thomas |   22 | F    |    178 |         5 |
| 10 | Tom    |   23 | F    |    164 |         5 |
| 11 | LiMing |   22 | M    |    180 |         7 |
+----+--------+------+------+--------+-----------+
11 rows in set (0.00 sec)

恢复差异备份

[root@node1 ~]# ll /opt/data/
total 123000
-rw-r-----. 1 mysql mysql    32247 Jun 30 21:05 apache.err
-rw-r-----. 1 mysql mysql       56 Jun 29 00:28 auto.cnf
-rw-------. 1 mysql mysql     1680 Jun 29 00:28 ca-key.pem
-rw-r--r--. 1 mysql mysql     1112 Jun 29 00:28 ca.pem
-rw-r--r--. 1 mysql mysql     1112 Jun 29 00:28 client-cert.pem
-rw-------. 1 mysql mysql     1676 Jun 29 00:28 client-key.pem
-rw-r-----. 1 mysql mysql      559 Jun 30 21:05 ib_buffer_pool
-rw-r-----. 1 mysql mysql 12582912 Jun 30 21:33 ibdata1
-rw-r-----. 1 mysql mysql 50331648 Jun 30 21:33 ib_logfile0
-rw-r-----. 1 mysql mysql 50331648 Jun 29 00:28 ib_logfile1
-rw-r-----. 1 mysql mysql 12582912 Jun 30 21:12 ibtmp1
drwxr-x---. 2 mysql mysql     4096 Jun 29 00:28 mysql
-rw-r-----. 1 mysql mysql     1460 Jun 30 21:34 mysql_bin.000002
-rw-r-----. 1 mysql mysql      154 Jun 30 21:34 mysql_bin.000003
-rw-r-----. 1 mysql mysql       38 Jun 30 21:34 mysql_bin.index
-rw-r-----. 1 mysql mysql        6 Jun 30 21:05 mysql.pid
-rw-r-----. 1 mysql mysql     3770 Jun 30 21:05 node1.err
drwxr-x---. 2 mysql mysql     8192 Jun 29 00:28 performance_schema
-rw-------. 1 mysql mysql     1680 Jun 29 00:28 private_key.pem
-rw-r--r--. 1 mysql mysql      452 Jun 29 00:28 public_key.pem
-rw-r--r--. 1 mysql mysql     1112 Jun 29 00:28 server-cert.pem
-rw-------. 1 mysql mysql     1676 Jun 29 00:28 server-key.pem
drwxr-x---. 2 mysql mysql     8192 Jun 29 00:28 sys
//检查误删数据库的位置在什么地方
mysql> show binlog events in 'mysql_bin.000002';
+------------------+------+----------------+-----------+-------------+-----------------------------------------------------------------------------------------------+
| Log_name         | Pos  | Event_type     | Server_id | End_log_pos | Info                                                                                          |
+------------------+------+----------------+-----------+-------------+-----------------------------------------------------------------------------------------------+
| mysql_bin.000002 |    4 | Format_desc    |         1 |         123 | Server ver: 5.7.37-log, Binlog ver: 4                                                         |
| mysql_bin.000002 |  123 | Previous_gtids |         1 |         154 |                                                                                               |
| mysql_bin.000002 |  154 | Anonymous_Gtid |         1 |         219 | SET @@SESSION.GTID_NEXT= 'ANONYMOUS'                                                          |
| mysql_bin.000002 |  219 | Query          |         1 |         376 | use `school`; create table info(id int primary key auto_increment,name varchar(100) not null) |
| mysql_bin.000002 |  376 | Anonymous_Gtid |         1 |         441 | SET @@SESSION.GTID_NEXT= 'ANONYMOUS'                                                          |
| mysql_bin.000002 |  441 | Query          |         1 |         515 | BEGIN                                                                                         |
| mysql_bin.000002 |  515 | Table_map      |         1 |         567 | table_id: 144 (school.info)                                                                   |
| mysql_bin.000002 |  567 | Write_rows     |         1 |         631 | table_id: 144 flags: STMT_END_F                                                               |
| mysql_bin.000002 |  631 | Xid            |         1 |         662 | COMMIT /* xid=502 */                                                                          |
| mysql_bin.000002 |  662 | Anonymous_Gtid |         1 |         727 | SET @@SESSION.GTID_NEXT= 'ANONYMOUS'                                                          |
| mysql_bin.000002 |  727 | Query          |         1 |         801 | BEGIN                                                                                         |
| mysql_bin.000002 |  801 | Table_map      |         1 |         871 | table_id: 143 (school.tb_students_info)                                                       |
| mysql_bin.000002 |  871 | Update_rows    |         1 |         947 | table_id: 143 flags: STMT_END_F                                                               |
| mysql_bin.000002 |  947 | Xid            |         1 |         978 | COMMIT /* xid=506 */                                                                          |
| mysql_bin.000002 |  978 | Anonymous_Gtid |         1 |        1043 | SET @@SESSION.GTID_NEXT= 'ANONYMOUS'                                                          |
| mysql_bin.000002 | 1043 | Query          |         1 |        1117 | BEGIN                                                                                         |
| mysql_bin.000002 | 1117 | Table_map      |         1 |        1174 | table_id: 142 (school.tb_course)                                                              |
| mysql_bin.000002 | 1174 | Delete_rows    |         1 |        1219 | table_id: 142 flags: STMT_END_F                                                               |
| mysql_bin.000002 | 1219 | Xid            |         1 |        1250 | COMMIT /* xid=509 */                                                                          |
| mysql_bin.000002 | 1250 | Anonymous_Gtid |         1 |        1315 | SET @@SESSION.GTID_NEXT= 'ANONYMOUS'                                                          |
| mysql_bin.000002 | 1315 | Query          |         1 |        1413 | drop database school                                                                          |
| mysql_bin.000002 | 1413 | Rotate         |         1 |        1460 | mysql_bin.000003;pos=4                                                                        |
+------------------+------+----------------+-----------+-------------+-----------------------------------------------------------------------------------------------+
22 rows in set (0.01 sec)

//使用mysqlbinlog恢复差异备份
[root@node1 ~]# mysqlbinlog --stop-position=1315 /opt/data/mysql_bin.000002 | mysql -uroot -plch123
mysql: [Warning] Using a password on the command line interface can be insecure.
mysql> show tables;
+------------------+
| Tables_in_school |
+------------------+
| info             |
| tb_course        |
| tb_students_info |
+------------------+
3 rows in set (0.00 sec)
mysql> select * from tb_students_info;
+----+--------+------+------+--------+-----------+
| id | name   | age  | sex  | height | course_id |
+----+--------+------+------+--------+-----------+
|  1 | Dany   |   25 | M    |    160 |         1 |
|  2 | Green  |   23 | M    |    158 |         2 |
|  3 | Henry  |   23 | F    |    185 |         1 |
|  4 | Jane   |   23 | F    |    162 |         3 |
|  5 | Jim    |   24 | F    |    175 |         2 |
|  6 | John   |   21 | F    |    172 |         4 |
|  7 | Lily   |   22 | M    |    165 |         4 |
|  8 | Susan  |   23 | M    |    170 |         5 |
|  9 | Thomas |   22 | F    |    178 |         5 |
| 10 | Tom    |   50 | F    |    164 |         5 |
| 11 | LiMing |   22 | M    |    180 |         7 |
+----+--------+------+------+--------+-----------+
11 rows in set (0.00 sec)

mysql> select * from tb_course;
+----+-------------+
| id | course_name |
+----+-------------+
|  1 | Java        |
|  2 | Mysql       |
|  3 | Python      |
|  4 | Go          |
|  5 | C++         |
+----+-------------+
5 rows in set (0.00 sec)

mysql> select * from info;
+----+-------+
| id | name  |
+----+-------+
|  1 | tom   |
|  2 | jerry |
|  3 | bob   |
+----+-------+
3 rows in set (0.00 sec)

破解密码步骤

步骤详解

  1. 修改配置文件,在配置文件中加入下行 skip-grant-tables (只能用root用户来操作)

    root@lch ~]# cat /etc/my.cnf 
    [mysqld]
    basedir = /usr/local/mysql
    datadir = /opt/data
    socket = /tmp/mysql.sock
    port = 3306
    pid-file = /opt/data/mysql.pid
    user = mysql
    skip-name-resolve
    skip-grant-tables
    
    
  2. 重启数据库 service mysqld restart

    [root@lch ~]# systemctl restart mysqld
    [root@lch ~]# ss -antl
    State      Recv-Q     Send-Q         Local Address:Port          Peer Address:Port     Process     
    LISTEN     0          128                  0.0.0.0:22                 0.0.0.0:*                    
    LISTEN     0          80                         *:3306                     *:*                    
    LISTEN     0          128                     [::]:22                    [::]:*  
    
  3. 登录数据库(此时不需要密码)

    [root@lch ~]# mysql
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 2
    Server version: 5.7.37 MySQL Community Server (GPL)
    
    Copyright (c) 2000, 2022, 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> 
    
  4. 修改密码

    mysql> use mysql;
    Reading table information for completion of table and column names
    You can turn off this feature to get a quicker startup with -A
    
    Database changed
    mysql>  update user set authentication_string = password('123456') where User = 'root' and Host = 'localhost';
    Query OK, 1 row affected, 1 warning (0.00 sec)
    Rows matched: 1  Changed: 1  Warnings: 1
    
  5. 把配置文件还原(即把之前添加的文件加上#注释掉即可)

    [root@lch ~]# vi /etc/my.cnf 
    [mysqld]
    basedir = /usr/local/mysql
    datadir = /opt/data
    socket = /tmp/mysql.sock
    port = 3306
    pid-file = /opt/data/mysql.pid
    user = mysql
    skip-name-resolve
    
  6. 重启数据库

    [root@lch ~]# systemctl restart mysqld
    [root@lch ~]# ss -antl
    State      Recv-Q     Send-Q         Local Address:Port          Peer Address:Port     Process     
    LISTEN     0          128                  0.0.0.0:22                 0.0.0.0:*                    
    LISTEN     0          80                         *:3306                     *:*                    
    LISTEN     0          128                     [::]:22                    [::]:*                   
    [root@lch ~]# mysql -uroot -p'123456'
    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 2
    Server version: 5.7.37 MySQL Community Server (GPL)
    
    Copyright (c) 2000, 2022, 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> 
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值