3-2.sql语言(续)
3.5 DDL 语句
DDL语句主要用来操作数据库中的表。
同一个库中不同表可以使用不同的存储引擎,但建议使用同一种存储引擎。
3.5.1创建表
格式
bash
#帮助
mysql> help create table
Name: 'CREATE TABLE'
Description:
Syntax:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
[table_options]
[partition_options]
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
[partition_options]
[IGNORE | REPLACE]
[AS] query_expression
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
{ LIKE old_tbl_name | (LIKE old_tbl_name) }
.....
直接创建
bash
CREATE TABLE [IF NOT EXISTS] 'tbl_name' (col1 type1 修饰符,col2 type2 修饰符,...)
#字段格式
col type1 #定义字段数据类型
PRIMARY KEY(col1,...) #将该字段设为主键
INDEX(col1,...) #设置为索引
UNIQUE KEY(COL1,...) #设置为联合主键
#表选项
ENGINE [=] engine_name
ROW_FORMAT [=] {DEFAULT|DYNAMIC|FIXED|COMPRESSED|REDUNDANT|COMPACT}
范例
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;
#选择数据库
mysql> use db1;
Database changed
#执行SQL语句
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> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| student |
+---------------+
1 row in set (0.00 sec)
#查看结构
mysql> desc student;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
#插入一条数据
mysql> insert student (name,age)values('xiaoming',20);
Query OK, 1 row affected (0.01 sec)
#查询表中的所有数据
mysql> select * from student;
+----+----------+------+--------+
| id | name | age | gender |
+----+----------+------+--------+
| 10 | xiaoming | 20 | M |
+----+----------+------+--------+
1 row in set (0.00 sec)
#再次插入一条数据
mysql> insert student(name,age,gender)values('xiaohong',18,'f');
Query OK, 1 row affected (0.00 sec)
mysql> select * from student;
+----+----------+------+--------+
| id | name | age | gender |
+----+----------+------+--------+
| 10 | xiaoming | 20 | M |
| 11 | xiaohong | 18 | F |
+----+----------+------+--------+
2 rows in set (0.00 sec)
通过查询现存表创建,新表会被直接插入查询而来的数据
范例
bash
mysql> desc student;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
#查询其他表创建
mysql> create table student2 select name,age from student;
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0
#查看
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| student |
| student2 |
+---------------+
2 rows in set (0.00 sec)
#查看结构
mysql> desc student2;
+-------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
+-------+------------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
#数据也复制过来了
mysql> select * from student2;
+----------+------+
| name | age |
+----------+------+
| xiaoming | 20 |
| xiaohong | 18 |
+----------+------+
2 rows in set (0.00 sec)
通过复制现存的表的表结构创建,但不复制数据
范例
mysql
mysql> desc student;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
mysql> create table student3 like student;
Query OK, 0 rows affected (0.01 sec)
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| student |
| student2 |
| student3 |
+---------------+
3 rows in set (0.00 sec)
mysql> desc student3;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
mysql> select * from student3;
Empty set (0.00 sec)
3.5.2查看表
格式
bash
mysql> help show tables
Name: 'SHOW TABLES'
Description:
Syntax:
SHOW [EXTENDED] [FULL] TABLES
[{FROM | IN} db_name]
[LIKE 'pattern' | WHERE expr]
列出数据库中的表
格式
bash
SHOW TABLES [FROM db_name]
范例
bash
#查看当前库中所有表
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| student |
| student2 |
| student3 |
+---------------+
3 rows in set (0.00 sec)
#查看指定库中的表
mysql> show tables from db1;
+---------------+
| Tables_in_db1 |
+---------------+
| student |
| student2 |
| student3 |
+---------------+
3 rows in set (0.00 sec)
查看建表语句
格式
bash
SHOW CREATE TABLE [db_name.]tbl_name
范例
bash
mysql> show create table student;
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| student | 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 AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
#查看指定数据库的数据表
mysql> show create table db1.student\G
*************************** 1. row ***************************
Table: student
Create Table: 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 AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
1 row in set (0.00 sec)
查看表结构
格式
bash
DESC [db_name.]tbl_name
SHOW COLUMNS FROM [db_name.]tbl_name
范例
bash
mysql> desc student;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
mysql> show columns from student;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
查看表状态
格式
bash
SHOW TABLE STATUS LIKE 'tbl_name'
范例
bash
mysql> SHOW TABLE STATUS LIKE 'student';
+---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment |
+---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
| student | InnoDB | 10 | Dynamic | 2 | 8192 | 16384 | 0 | 0 | 0 | 12 | 2025-09-18 22:10:21 | 2025-09-18 22:24:45 | NULL | utf8mb4_0900_ai_ci | NULL | | |
+---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
1 row in set (0.00 sec)
mysql> SHOW TABLE STATUS LIKE 'student'\G
*************************** 1. row ***************************
Name: student
Engine: InnoDB
Version: 10
Row_format: Dynamic
Rows: 2
Avg_row_length: 8192
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 0
Auto_increment: 12
Create_time: 2025-09-18 22:10:21
Update_time: 2025-09-18 22:24:45
Check_time: NULL
Collation: utf8mb4_0900_ai_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.01 sec)
#不能有库名
mysql> SHOW TABLE STATUS LIKE 'db1.student'\G
Empty set (0.00 sec)
查看库中所有表状态
格式
mysql
SHOW TABLE STATUS FROM db_name
范例
bash
mysql> SHOW TABLE STATUS FROM db1\G
*************************** 1. row ***************************
Name: student
Engine: InnoDB
Version: 10
Row_format: Dynamic
Rows: 2
Avg_row_length: 8192
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 0
Auto_increment: 12
Create_time: 2025-09-18 22:10:21
Update_time: 2025-09-18 22:24:45
Check_time: NULL
Collation: utf8mb4_0900_ai_ci
Checksum: NULL
Create_options:
Comment:
*************************** 2. row ***************************
Name: student2
Engine: InnoDB
Version: 10
Row_format: Dynamic
Rows: 2
Avg_row_length: 8192
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 0
Auto_increment: NULL
Create_time: 2025-09-18 22:35:06
Update_time: 2025-09-18 22:35:06
Check_time: NULL
Collation: utf8mb4_0900_ai_ci
Checksum: NULL
Create_options:
Comment:
*************************** 3. row ***************************
Name: student3
Engine: InnoDB
Version: 10
Row_format: Dynamic
Rows: 0
Avg_row_length: 0
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 0
Auto_increment: 1
Create_time: 2025-09-18 22:49:14
Update_time: NULL
Check_time: NULL
Collation: utf8mb4_0900_ai_ci
Checksum: NULL
Create_options:
Comment:
3 rows in set (0.01 sec)
查看当前MySQL服务支持的引擎
格式
mysql
SHOW ENGINES
范例
mysql
mysql> mysql> SHOW ENGINES;
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Engine | Support | Comment | Transactions | XA | Savepoints |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| FEDERATED | NO | Federated MySQL storage engine | NULL | NULL | NULL |
| MEMORY | YES | Hash based, stored in memory, useful for temporary tables | NO | NO | NO |
| InnoDB | DEFAULT | Supports transactions, row-level locking, and foreign keys | YES | YES | YES |
| PERFORMANCE_SCHEMA | YES | Performance Schema | NO | NO | NO |
| MyISAM | YES | MyISAM storage engine | NO | NO | NO |
| MRG_MYISAM | YES | Collection of identical MyISAM tables | NO | NO | NO |
| BLACKHOLE | YES | /dev/null storage engine (anything you write to it disappears) | NO | NO | NO |
| CSV | YES | CSV storage engine | NO | NO | NO |
| ARCHIVE | YES | Archive storage engine | NO | NO | NO |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
9 rows in set (0.01 sec)
mysql> SHOW ENGINES\G
*************************** 1. row ***************************
Engine: FEDERATED
Support: NO
Comment: Federated MySQL storage engine
Transactions: NULL
XA: NULL
Savepoints: NULL
*************************** 2. row ***************************
Engine: MEMORY
Support: YES
Comment: Hash based, stored in memory, useful for temporary tables
Transactions: NO
XA: NO
Savepoints: NO
*************************** 3. row ***************************
Engine: InnoDB
Support: DEFAULT
Comment: Supports transactions, row-level locking, and foreign keys
Transactions: YES
XA: YES
Savepoints: YES
*************************** 4. row ***************************
Engine: PERFORMANCE_SCHEMA
Support: YES
Comment: Performance Schema
Transactions: NO
XA: NO
Savepoints: NO
*************************** 5. row ***************************
Engine: MyISAM
Support: YES
Comment: MyISAM storage engine
Transactions: NO
XA: NO
Savepoints: NO
*************************** 6. row ***************************
Engine: MRG_MYISAM
Support: YES
Comment: Collection of identical MyISAM tables
Transactions: NO
XA: NO
Savepoints: NO
*************************** 7. row ***************************
Engine: BLACKHOLE
Support: YES
Comment: /dev/null storage engine (anything you write to it disappears)
Transactions: NO
XA: NO
Savepoints: NO
*************************** 8. row ***************************
Engine: CSV
Support: YES
Comment: CSV storage engine
Transactions: NO
XA: NO
Savepoints: NO
*************************** 9. row ***************************
Engine: ARCHIVE
Support: YES
Comment: Archive storage engine
Transactions: NO
XA: NO
Savepoints: NO
9 rows in set (0.00 sec)
3.5.3修改和删除表
mysql
ALTER TABLE tbl_name
[alter_option [, alter_option] ...]
[partition_options]
mysql
{ ADD COLUMN <列名> <类型>
| CHANGE COLUMN <旧列名> <新列名> <新列类型>
| ALTER COLUMN <列名> { SET DEFAULT <默认值>丨DROP DEFAULT }
| MODIFY COLUMN <列名> <类型>
| DROP COLUMN <列名>
| RENAME TO <新表名> }
范例
bash
#修改表名
mysql> ALTER TABLE student RENAME stu;
Query OK, 0 rows affected (0.01 sec)
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| stu |
| student2 |
| student3 |
+---------------+
3 rows in set (0.00 sec)
mysql> desc stu;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
#添加表字段
mysql> ALTER TABLE stu ADD phone varchar(11) AFTER name;
Query OK, 0 rows affected (0.01 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 MODIFY phone int;
Query OK, 2 rows affected (0.01 sec)
Records: 2 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 | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
#修改字段名称和类型
mysql> ALTER TABLE stu CHANGE COLUMN phone mobile char(11);
Query OK, 2 rows affected (0.02 sec)
Records: 2 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 | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
#删除字段
mysql> ALTER TABLE stu DROP COLUMN mobile;
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 | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
#修改表字符集
mysql> ALTER TABLE stu character SET utf8;
Query OK, 0 rows affected, 1 warning (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 1
#同时修改数据类型和字符集,只修改字符集,类型也不能少
mysql> ALTER TABLE stu CHANGE name name char(30) character set utf8;
Query OK, 2 rows affected, 1 warning (0.02 sec)
Records: 2 Duplicates: 0 Warnings: 1
#设置字段默认值
mysql> alter table stu alter column gender set default 'M';
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
#添加字段和修改字段
mysql> ALTER TABLE stu ADD is_del bool DEFAULT false;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> ALTER TABLE stu modify is_del bool DEFAULT true;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
范例
bash
mysql> create table stu2 select * from stu;
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> desc stu2;
+--------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+-------+
| id | int unsigned | NO | | 0 | |
| name | char(30) | YES | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
| is_del | tinyint(1) | YES | | 1 | |
+--------+------------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
#添加主键
mysql> ALTER TABLE stu2 ADD PRIMARY KEY (id);
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc stu2;
+--------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+-------+
| id | int unsigned | NO | PRI | 0 | |
| name | char(30) | YES | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
| is_del | tinyint(1) | YES | | 1 | |
+--------+------------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
#删除主键
mysql> ALTER TABLE stu2 DROP PRIMARY KEY;
Query OK, 2 rows affected (0.02 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> desc stu2;
+--------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+-------+
| id | int unsigned | NO | | 0 | |
| name | char(30) | YES | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| gender | enum('M','F') | YES | | M | |
| is_del | tinyint(1) | YES | | 1 | |
+--------+------------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
删除表
格式
bash
DROP [TEMPORARY] TABLE [IF EXISTS]
tbl_name [, tbl_name] ...
[RESTRICT | CASCADE]
范例
bash
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| stu |
| stu2 |
| student2 |
| student3 |
+---------------+
4 rows in set (0.00 sec)
mysql> drop table student2;drop table db1.student3;
Query OK, 0 rows affected (0.01 sec)
Query OK, 0 rows affected (0.01 sec)
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| stu |
| stu2 |
+---------------+
2 rows in set (0.00 sec)
3.6 DML 语句
DML语句包括INSERT,UDPATE,DELETE
3.6.1插入数据
INSERT可以一次往表中插入一条或多条记录
格式
bash
mysql> help INSERT
Name: 'INSERT'
Description:
Syntax:
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name [, partition_name] ...)]
[(col_name [, col_name] ...)]
{ {VALUES | VALUE} (value_list) [, (value_list)] ...
|
VALUES row_constructor_list
}
[AS row_alias[(col_alias [, col_alias] ...)]]
[ON DUPLICATE KEY UPDATE assignment_list]
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name [, partition_name] ...)]
[AS row_alias[(col_alias [, col_alias] ...)]]
SET assignment_list
[ON DUPLICATE KEY UPDATE assignment_list]
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name [, partition_name] ...)]
[(col_name [, col_name] ...)]
[AS row_alias[(col_alias [, col_alias] ...)]]
{SELECT ... | TABLE table_name}
[ON DUPLICATE KEY UPDATE assignment_list]
简化格式
bash
INSERT tbl_name [(col1,...)] VALUES (val1,...),(val21,...)
范例
bash
mysql> insert into stu values(10,'xiaoming',20,'M',0);
Query OK, 1 row affected (0.01 sec)
mysql> insert into stu values(11,'xiaohong',18,'F',0);
Query OK, 1 row affected (0.01 sec)
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 20 | M | 0 |
| 11 | xiaohong | 18 | F | 0 |
+----+----------+------+--------+--------+
2 rows in set (0.00 sec)
#给出所有字段值(给出所有字段值,可以不用标明字段,只要顺序一一对应即可)
mysql> INSERT INTO stu VALUES(12,'xiaoli',19,'F',0);
Query OK, 1 row affected (0.01 sec
#只给出部分字段值,因为有些字段值有默认值
mysql> INSERT INTO stu(name,age)VALUES('xiaozhou',20);
Query OK, 1 row affected (0.02 sec)
#一次插入多条
mysql> INSERT INTO stu (name,age)VALUES('test1',20),('test2',21),('test3',22);
Query OK, 3 rows affected (0.01 sec)
Records: 3 Duplicates: 0 Warnings: 0
#有默认值的用默认值,没有默认值的用NULL值
mysql> INSERT stu (age,is_del)VALUES(23,0);
Query OK, 1 row affected (0.00 sec)
#查看
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 20 | M | 0 |
| 11 | xiaohong | 18 | F | 0 |
| 12 | xiaoli | 19 | F | 0 |
| 13 | xiaozhou | 20 | M | 1 |
| 14 | test1 | 20 | M | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 22 | M | 1 |
| 17 | NULL | 23 | M | 0 |
+----+----------+------+--------+--------+
8 rows in set (0.00 sec)
#如果记录不存在就新增,如果存在就更新
mysql> SELECT * FROM stu WHERE id=12;
+----+--------+------+--------+--------+
| id | name | age | gender | is_del |
+----+--------+------+--------+--------+
| 12 | xiaoli | 19 | F | 0 |
+----+--------+------+--------+--------+
1 row in set (0.00 sec)
mysql> INSERT INTO stu (id,name)VALUES(12,'zhangsan');
ERROR 1062 (23000): Duplicate entry '12' for key 'stu.PRIMARY'
mysql> INSERT INTO stu (id,name)VALUES(12,'zhangsan') ON DUPLICATE KEY UPDATE name='zhangsan';
Query OK, 2 rows affected (0.00 sec)
mysql> SELECT * FROM stu WHERE id=12;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 12 | zhangsan | 19 | F | 0 |
+----+----------+------+--------+--------+
1 row in set (0.00 sec)
#将查询结果当值插入
mysql> insert into stu (name,age,gender) select name,age,gender from stu where id=11;
Query OK, 1 row affected (0.01 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 20 | M | 0 |
| 11 | xiaohong | 18 | F | 0 |
| 12 | zhangsan | 19 | F | 0 |
| 13 | xiaozhou | 20 | M | 1 |
| 14 | test1 | 20 | M | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 22 | M | 1 |
| 17 | NULL | 23 | M | 0 |
| 18 | xiaohong | 18 | F | 1 |
+----+----------+------+--------+--------+
9 rows in set (0.00 sec)
mysql> insert into stu (name,age,gender) select name,age,gender from stu where id in (11,12);
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 20 | M | 0 |
| 11 | xiaohong | 18 | F | 0 |
| 12 | zhangsan | 19 | F | 0 |
| 13 | xiaozhou | 20 | M | 1 |
| 14 | test1 | 20 | M | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 22 | M | 1 |
| 17 | NULL | 23 | M | 0 |
| 18 | xiaohong | 18 | F | 1 |
| 19 | xiaohong | 18 | F | 1 |
| 20 | zhangsan | 19 | F | 1 |
+----+----------+------+--------+--------+
11 rows in set (0.00 sec)
3.6.2 更新数据
更新数据一定要加条件限制,没有条件则会更新表中所有记录。
mysql
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET assignment_list
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
范例
bash
#不加条件表示更新所有
mysql> UPDATE stu set age=30,gender='F';
Query OK, 11 rows affected (0.00 sec)
Rows matched: 11 Changed: 11 Warnings: 0
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 30 | F | 0 |
| 11 | xiaohong | 30 | F | 0 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 30 | F | 1 |
| 16 | test3 | 30 | F | 1 |
| 17 | NULL | 30 | F | 0 |
| 18 | xiaohong | 30 | F | 1 |
| 19 | xiaohong | 30 | F | 1 |
| 20 | zhangsan | 30 | F | 1 |
+----+----------+------+--------+--------+
11 rows in set (0.00 sec)
#根据条件更新
mysql> update stu set age=31 WHERE id>15;
Query OK, 5 rows affected (0.01 sec)
Rows matched: 5 Changed: 5 Warnings: 0
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 30 | F | 0 |
| 11 | xiaohong | 30 | F | 0 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 30 | F | 1 |
| 16 | test3 | 31 | F | 1 |
| 17 | NULL | 31 | F | 0 |
| 18 | xiaohong | 31 | F | 1 |
| 19 | xiaohong | 31 | F | 1 |
| 20 | zhangsan | 31 | F | 1 |
+----+----------+------+--------+--------+
11 rows in set (0.00 sec)
#多个条件,满足任何一个条件都更新 OR 可以写成 ||
mysql> update stu set age=21,gender='M' where (id=15 OR name is null);
Query OK, 2 rows affected (0.01 sec)
Rows matched: 2 Changed: 2 Warnings: 0
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 30 | F | 0 |
| 11 | xiaohong | 30 | F | 0 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 31 | F | 1 |
| 17 | NULL | 21 | M | 0 |
| 18 | xiaohong | 31 | F | 1 |
| 19 | xiaohong | 31 | F | 1 |
| 20 | zhangsan | 31 | F | 1 |
+----+----------+------+--------+--------+
11 rows in set (0.00 sec)
#多个条件满足,AND 可以写成 &&
mysql> update stu set age=22,gender='M' WHERE (id=17 AND name is null);
Query OK, 1 row affected (0.02 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 30 | F | 0 |
| 11 | xiaohong | 30 | F | 0 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 31 | F | 1 |
| 17 | NULL | 22 | M | 0 |
| 18 | xiaohong | 31 | F | 1 |
| 19 | xiaohong | 31 | F | 1 |
| 20 | zhangsan | 31 | F | 1 |
+----+----------+------+--------+--------+
11 rows in set (0.00 sec)
#NULL要写 IS NULL
mysql> update stu set gender='F' where name=NULL;
Query OK, 0 rows affected (0.01 sec)
Rows matched: 0 Changed: 0 Warnings: 0
mysql> update stu set gender='F' where name IS NULL;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0
保证无法在没有条件的情况下更新所有
bash
-U, --i-am-a-dummy Synonym for option --safe-updates, -U.
[root@localhost ~]# mysql -U
#该配置还可以写到配置文件中
[root@localhost ~]# vim /etc/my.cnf.d/client.cnf
[client]
safe-updates
#无法完全更新
mysql> update stu set age=22;
ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column.
mysql> update stu set age=23 where name='test3';
ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column.
#必须要指定主键
mysql> UPDATE stu SET age=23 WHERE id=17;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 30 | F | 0 |
| 11 | xiaohong | 30 | F | 0 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 31 | F | 1 |
| 17 | NULL | 23 | F | 0 |
| 18 | xiaohong | 31 | F | 1 |
| 19 | xiaohong | 31 | F | 1 |
| 20 | zhangsan | 31 | F | 1 |
+----+----------+------+--------+--------+
11 rows in set (0.00 sec)
3.6.3 删除数据
格式
bash
DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
tbl_name[.*] [, tbl_name[.*]] ...
FROM table_references
[WHERE where_condition]
DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
FROM tbl_name[.*] [, tbl_name[.*]] ...
USING table_references
[WHERE where_condition]
范例
bash
#查看全部数据
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 10 | xiaoming | 30 | F | 0 |
| 11 | xiaohong | 30 | F | 0 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 31 | F | 1 |
| 17 | NULL | 23 | F | 0 |
| 18 | xiaohong | 31 | F | 1 |
| 19 | xiaohong | 31 | F | 1 |
| 20 | zhangsan | 31 | F | 1 |
+----+----------+------+--------+--------+
11 rows in set (0.00 sec)
#根据条件删除
mysql> delete from stu where id=10;
Query OK, 1 row affected (0.00 sec)
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 11 | xiaohong | 30 | F | 0 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 31 | F | 1 |
| 17 | NULL | 23 | F | 0 |
| 18 | xiaohong | 31 | F | 1 |
| 19 | xiaohong | 31 | F | 1 |
| 20 | zhangsan | 31 | F | 1 |
+----+----------+------+--------+--------+
10 rows in set (0.00 sec)
在直实生产环境中,一般不会对数据做物理删除,而是用字段来标记为逻辑删除,将对应字段值设为某个特定项(is_del ),(is_del=1)认为是己删除
bash
mysql> UPDATE stu SET is_del=1 WHERE id=11;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1 Changed: 0 Warnings: 0
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 11 | xiaohong | 30 | F | 1 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 31 | F | 1 |
| 17 | NULL | 23 | F | 0 |
| 18 | xiaohong | 31 | F | 1 |
| 19 | xiaohong | 31 | F | 1 |
| 20 | zhangsan | 31 | F | 1 |
+----+----------+------+--------+--------+
10 rows in set (0.00 sec)
清空表
bash
TRUNCATE TABLE tbl_name; #DDL语句,不支持事务,效率更高
DELETE FROM tbl_name; #DML语句
3.7 DQL 语句
格式
bash
mysql> help select
Name: 'SELECT'
Description:
Syntax:
SELECT
[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
[SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr [, select_expr] ...
[into_option]
[FROM table_references
[PARTITION partition_list]]
[WHERE where_condition]
[GROUP BY {col_name | expr | position}, ... [WITH ROLLUP]]
[HAVING where_condition]
[WINDOW window_name AS (window_spec)
[, window_name AS (window_spec)] ...]
[ORDER BY {col_name | expr | position}
[ASC | DESC], ... [WITH ROLLUP]]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[into_option]
[FOR {UPDATE | SHARE}
[OF tbl_name [, tbl_name] ...]
[NOWAIT | SKIP LOCKED]
| LOCK IN SHARE MODE]
[into_option]
into_option: {
INTO OUTFILE 'file_name'
[CHARACTER SET charset_name]
export_options
| INTO DUMPFILE 'file_name'
| INTO var_name [, var_name] ...
}
说明
字段显示可以使用别名:col1 AS alias1,col2 AS alias2,...
WHERE子句:指明过滤条件以实现"选择"的功能
过滤条件:布尔型表达式
算术操作符:+,-,*,/,%
比较操作符:=,<=>(相等或都为空),<>,!=(非标准SQL,>,>=,<,<=
范围查询:BETWEEN min_num AND max_num
不连续的查询:IN(element1,element2,...)
空查询:IS NULL,,IS NOT NULL
DISTINCT去除重复行,范例:SELECT DISTINCT gender FROM students;
模糊查询:LIKE使用%表示任意长度的任意字符_表示任意单个字符
RLIKE:正则表达式,索引失效,不建议使用
REGEXP:匹配字符串可用正则表达式书写模式,同上
逻辑操作符:NOT,AND,OR,XOR
GROUPBY:根据指定的条件把查询结果进行"分组"以用于做"聚合"运算
常见聚合函数:count),sum(),max(),min(),avg(),注意:聚合函数不对null统计
HAVING:对分组聚合运算后的结果指定过滤条件
一旦分组group by,select语句后只跟分组的字段,聚合函数
ORDERBY:根据指定的字段对查询结果进行排序
升序:ASC
降序:DESC
LIMIT[offset,]row_count]:对查询的结果进行输出行数数量限制,跳过offset,显示row_count 行,offset默为值为0。
对查询结果中的数据请求施加"锁"
FOR UPDATE:写锁,独占或排它锁,只有一个读和写操作
LOCK IN SHARE MODE:读锁,共享锁,同时多个读操作
3.7.1单表操作
范例:查字符串和变量
bash
#直接查字符串
mysql> select 123;
+-----+
| 123 |
+-----+
| 123 |
+-----+
1 row in set (0.00 sec)
#指定别名
mysql> select 'xbq' as 'xiebaiqi';
+--------+
| xiebaiqi |
+--------+
| xbq |
+--------+
1 row in set (0.00 sec)
#数学计算
mysql> select 1+2*3;
+-------+
| 1+2*3 |
+-------+
| 7 |
+-------+
1 row in set (0.01 sec
#查询变量
mysql> select @@port;
+--------+
| @@port |
+--------+
| 3306 |
+--------+
1 row in set (0.01 sec)
#查询函数
mysql> select now();
+---------------------+
| now() |
+---------------------+
| 2025-09-21 20:52:19 |
+---------------------+
1 row in set (0.00 sec)
范例:指定字段和查询条件
bash
#全表扫描
mysql> select * from stu;
+----+----------+------+--------+--------+
| id | name | age | gender | is_del |
+----+----------+------+--------+--------+
| 11 | xiaohong | 30 | F | 1 |
| 12 | zhangsan | 30 | F | 0 |
| 13 | xiaozhou | 30 | F | 1 |
| 14 | test1 | 30 | F | 1 |
| 15 | test2 | 21 | M | 1 |
| 16 | test3 | 31 | F | 1 |
| 17 | NULL | 23 | F | 0 |
| 18 | xiaohong | 31 | F | 1 |
| 19 | xiaohong | 31 | F | 1 |
| 20 | zhangsan | 31 | F | 1 |
+----+----------+------+--------+--------+
10 rows in set (0.00 sec)
#查询指定字段
mysql> select id as 学号,name as 姓名,age as 年纪 from stu;
+--------+----------+--------+
| 学号 | 姓名 | 年纪 |
+--------+----------+--------+
| 11 | xiaohong | 30 |
| 12 | zhangsan | 30 |
| 13 | xiaozhou | 30 |
| 14 | test1 | 30 |
| 15 | test2 | 21 |
| 16 | test3 | 31 |
| 17 | NULL | 23 |
| 18 | xiaohong | 31 |
| 19 | xiaohong | 31 |
| 20 | zhangsan | 31 |
+--------+----------+--------+
10 rows in set (0.00 sec)
#根据条件查询
mysql> select id,name from stu where id=11;
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
+----+----------+
1 row in set (0.00 sec)
#多条
mysql> select id,name from stu where id in(11,15,19);
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 15 | test2 |
| 19 | xiaohong |
+----+----------+
3 rows in set (0.00 sec)
#and 可以写为 &&
mysql> select id,name from stu where id>=11 and id <14;
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 12 | zhangsan |
| 13 | xiaozhou |
+----+----------+
3 rows in set (0.00 sec)
#or 可以写为 ||
mysql> select id,name from stu where id<=12 or id>19;
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 12 | zhangsan |
| 20 | zhangsan |
+----+----------+
3 rows in set (0.00 sec)
范例:NULL值
bash
mysql> select id,name,age from stu where name=NUll; #语法错误
Empty set (0.01 sec)
#null值
mysql> select id,name,age from stu where name IS NULL;
+----+------+------+
| id | name | age |
+----+------+------+
| 17 | NULL | 23 |
+----+------+------+
1 row in set (0.00 sec)
#非null值
mysql> select id,name,age from stu where name is not null;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 11 | xiaohong | 30 |
| 12 | zhangsan | 30 |
| 13 | xiaozhou | 30 |
| 14 | test1 | 30 |
| 15 | test2 | 21 |
| 16 | test3 | 31 |
| 18 | xiaohong | 31 |
| 19 | xiaohong | 31 |
| 20 | zhangsan | 31 |
+----+----------+------+
9 rows in set (0.00 sec)
范例:模糊匹配
bash
#以指定字符开头
mysql> select id,name from stu where name like 'x%';
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 13 | xiaozhou |
| 18 | xiaohong |
| 19 | xiaohong |
+----+----------+
4 rows in set (0.00 sec)
#以指定字符开头
mysql> select id,name from stu where name like 'xiao%';
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 13 | xiaozhou |
| 18 | xiaohong |
| 19 | xiaohong |
+----+----------+
4 rows in set (0.00 sec)
#以指定字符结尾
mysql> select id,name from stu where name like '%ng';
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 18 | xiaohong |
| 19 | xiaohong |
+----+----------+
3 rows in set (0.00 sec)
#包含指定字符串
mysql> select id,name from stu where name like '%ou%';
+----+----------+
| id | name |
+----+----------+
| 13 | xiaozhou |
+----+----------+
1 row in set (0.00 sec)
#多个LIKE
mysql> select id,name from stu where name like '%n%' or name like '%i%';
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 12 | zhangsan |
| 13 | xiaozhou |
| 18 | xiaohong |
| 19 | xiaohong |
| 20 | zhangsan |
+----+----------+
6 rows in set (0.01 sec)
范例:区域间过滤
bash
#连续
mysql> select id,name from stu where id between 12 and 15;
+----+----------+
| id | name |
+----+----------+
| 12 | zhangsan |
| 13 | xiaozhou |
| 14 | test1 |
| 15 | test2 |
+----+----------+
4 rows in set (0.00 sec)
#取反
mysql> select id,name from stu where id not between 12 and 15;
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 16 | test3 |
| 17 | NULL |
| 18 | xiaohong |
| 19 | xiaohong |
| 20 | zhangsan |
+----+----------+
6 rows in set (0.00 sec)
#不连续
mysql> select id,name from stu where id in(12,15,19);
+----+----------+
| id | name |
+----+----------+
| 12 | zhangsan |
| 15 | test2 |
| 19 | xiaohong |
+----+----------+
3 rows in set (0.01 sec)
#不连续取反
mysql> select id,name from stu where id not in (12,15,19);
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 13 | xiaozhou |
| 14 | test1 |
| 16 | test3 |
| 17 | NULL |
| 18 | xiaohong |
| 20 | zhangsan |
+----+----------+
7 rows in set (0.00 sec)
范例:统计和分组
bash
#统计表中的记录条数
mysql> select count(*) as total from stu;
+-------+
| total |
+-------+
| 10 |
+-------+
1 row in set (0.00 sec)
#age字段中有null,不统计
mysql> select count(age) from stu;
+------------+
| count(age) |
+------------+
| 10 |
+------------+
1 row in set (0.00 sec)
mysql> select count(id) from stu;
+-----------+
| count(id) |
+-----------+
| 10 |
+-----------+
1 row in set (0.00 sec)
#最大值,最小值,平均值
mysql> select max(id),min(id),avg(age) from stu;
+---------+---------+----------+
| max(id) | min(id) | avg(age) |
+---------+---------+----------+
| 20 | 11 | 28.8000 |
+---------+---------+----------+
1 row in set (0.00 sec)
#求和
mysql> select sum(age) from stu;
+----------+
| sum(age) |
+----------+
| 288 |
+----------+
1 row in set (0.00 sec)
#分组统计
mysql> select sum(age),gender from stu group by gender;
+----------+--------+
| sum(age) | gender |
+----------+--------+
| 267 | F |
| 21 | M |
+----------+--------+
2 rows in set (0.01 sec)
#分组统计
mysql> select count(*),gender from stu group by gender;
+----------+--------+
| count(*) | gender |
+----------+--------+
| 9 | F |
| 1 | M |
+----------+--------+
2 rows in set (0.00 sec)
#分组带where条件
mysql> select count(*),max(id),avg(age),gender from stu where age is not null group by gender;
+----------+---------+----------+--------+
| count(*) | max(id) | avg(age) | gender |
+----------+---------+----------+--------+
| 9 | 20 | 29.6667 | F |
| 1 | 15 | 21.0000 | M |
+----------+---------+----------+--------+
2 rows in set (0.00 sec)
#分组后过滤
mysql> select count(*) as total,max(id),avg(age),gender from stu where age is not null group by gender having total=3;
Empty set (0.01 sec)
#分组统计
mysql> select count(*),max(id),avg(age),gender from stu group by gender;
+----------+---------+----------+--------+
| count(*) | max(id) | avg(age) | gender |
+----------+---------+----------+--------+
| 9 | 20 | 29.6667 | F |
| 1 | 15 | 21.0000 | M |
+----------+---------+----------+--------+
2 rows in set (0.00 sec)
范例:排序
bash
#默认按ID升序排列
mysql> select id,name,age from stu;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 11 | xiaohong | 30 |
| 12 | zhangsan | 30 |
| 13 | xiaozhou | 30 |
| 14 | test1 | 30 |
| 15 | test2 | 21 |
| 16 | test3 | 31 |
| 17 | NULL | 23 |
| 18 | xiaohong | 31 |
| 19 | xiaohong | 31 |
| 20 | zhangsan | 31 |
+----+----------+------+
10 rows in set (0.00 sec)
mysql> select id,name,age from stu order by id;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 11 | xiaohong | 30 |
| 12 | zhangsan | 30 |
| 13 | xiaozhou | 30 |
| 14 | test1 | 30 |
| 15 | test2 | 21 |
| 16 | test3 | 31 |
| 17 | NULL | 23 |
| 18 | xiaohong | 31 |
| 19 | xiaohong | 31 |
| 20 | zhangsan | 31 |
+----+----------+------+
10 rows in set (0.00 sec)
mysql> select id,name,age from stu order by id asc;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 11 | xiaohong | 30 |
| 12 | zhangsan | 30 |
| 13 | xiaozhou | 30 |
| 14 | test1 | 30 |
| 15 | test2 | 21 |
| 16 | test3 | 31 |
| 17 | NULL | 23 |
| 18 | xiaohong | 31 |
| 19 | xiaohong | 31 |
| 20 | zhangsan | 31 |
+----+----------+------+
10 rows in set (0.00 sec)
#降序
mysql> select id,name,age from stu order by id desc;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 20 | zhangsan | 31 |
| 19 | xiaohong | 31 |
| 18 | xiaohong | 31 |
| 17 | NULL | 23 |
| 16 | test3 | 31 |
| 15 | test2 | 21 |
| 14 | test1 | 30 |
| 13 | xiaozhou | 30 |
| 12 | zhangsan | 30 |
| 11 | xiaohong | 30 |
+----+----------+------+
10 rows in set (0.00 sec)
#降序变升序
mysql> select id,name,age from stu order by -id desc;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 11 | xiaohong | 30 |
| 12 | zhangsan | 30 |
| 13 | xiaozhou | 30 |
| 14 | test1 | 30 |
| 15 | test2 | 21 |
| 16 | test3 | 31 |
| 17 | NULL | 23 |
| 18 | xiaohong | 31 |
| 19 | xiaohong | 31 |
| 20 | zhangsan | 31 |
+----+----------+------+
10 rows in set (0.00 sec)
#用分组结果排序
mysql> select sum(age) sum_age,avg(age) avg_age,gender from stu where age is not null group by gender order by sum_age asc;
+---------+---------+--------+
| sum_age | avg_age | gender |
+---------+---------+--------+
| 21 | 21.0000 | M |
| 267 | 29.6667 | F |
+---------+---------+--------+
2 rows in set (0.00 sec)
范例:去重
bash
mysql> select id,name,age from stu order by age desc;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 16 | test3 | 31 |
| 18 | xiaohong | 31 |
| 19 | xiaohong | 31 |
| 20 | zhangsan | 31 |
| 11 | xiaohong | 30 |
| 12 | zhangsan | 30 |
| 13 | xiaozhou | 30 |
| 14 | test1 | 30 |
| 17 | NULL | 23 |
| 15 | test2 | 21 |
+----+----------+------+
10 rows in set (0.00 sec)
#去重
mysql> select distinct age from stu order by age desc;
+------+
| age |
+------+
| 31 |
| 30 |
| 23 |
| 21 |
+------+
4 rows in set (0.00 sec)
#去重
mysql> select distinct(age) from stu order by age desc;
+------+
| age |
+------+
| 31 |
| 30 |
| 23 |
| 21 |
+------+
4 rows in set (0.00 sec)
范例:分页
bash
mysql> select id,name from stu;
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 12 | zhangsan |
| 13 | xiaozhou |
| 14 | test1 |
| 15 | test2 |
| 16 | test3 |
| 17 | NULL |
| 18 | xiaohong |
| 19 | xiaohong |
| 20 | zhangsan |
+----+----------+
10 rows in set (0.00 sec)
#第一页,每页3条记录
mysql> select id,name from stu limit 0,3;
+----+----------+
| id | name |
+----+----------+
| 11 | xiaohong |
| 12 | zhangsan |
| 13 | xiaozhou |
+----+----------+
3 rows in set (0.00 sec)
#第二页,每页3条记录
mysql> select id,name from stu limit 3,3;
+----+-------+
| id | name |
+----+-------+
| 14 | test1 |
| 15 | test2 |
| 16 | test3 |
+----+-------+
3 rows in set (0.00 sec)
#第三页,每页3条记录
mysql> select id,name from stu limit 6,3;
+----+----------+
| id | name |
+----+----------+
| 17 | NULL |
| 18 | xiaohong |
| 19 | xiaohong |
+----+----------+
3 rows in set (0.01 sec)
3.8 MySQL用户管理
MySQL服务的账户是独立存在的,只用于MySQL服务的登录验证。
虚拟用户:给服务和应用使用的用户账号。
系统用户:Linux系统使用的用户账号
在MySQL服务中,用户组成包括用户名,主机,密码等。
Host指主机,表示只有在该主机上,才能使用对应的账号连接MySQL服务器,主机限制了账号可以登录的位置。用户名可以相同,主机也可以相同,用户名和主机组合起来才能标识一个唯一用户。
其它数据库系统,例如SQLServer,Oracle等都没有此限制,只要账号和密码能校验通过即可登录。这也是MySQL与其它数据库系统的一个不同之处。
Host可以写成主机名,IP地址,网段。可以用%,_来表示通配符,%表示任意长度的任意字符,_表示一个字符。
范例:
bash
#主机名
xbq@'mysql.xiebaiqi.cloud'
xbq'localhost'
#IP地址
xbq@'10.0.0.110'
xbq@'172.16.10.110'
#网段
xbq@′10.0.0.0/255.255.0.0'
xbq@′172.16.10.0/255.255.255.0'
#通配符
xbq@′10.0.%.%
xbq@'172.16._.%'
MySQL8.0中默认没有可以远程登陆的用户
bash
mysql> use mysql;
#前三个是MySQL服务自身使用
mysql> select Host,User from user;
+-----------+------------------+
| Host | User |
+-----------+------------------+
| localhost | mysql.infoschema |
| localhost | mysql.session |
| localhost | mysql.sys |
| localhost | root |
+-----------+------------------+
4 rows in set (0.00 sec)
#现在使用的是第四个
mysql> select user();
+----------------+
| user() |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)
mysql> status
--------------
mysql Ver 8.0.26 for Linux on x86_64 (Source distribution)
Connection id: 18
Current database:
Current user: root@localhost
SSL: Not in use
Current pager: stdout
Using outfile: ''
Using delimiter: ;
Server version: 8.0.26 Source distribution
Protocol version: 10
Connection: Localhost via UNIX socket
Server characterset: latin1
Db characterset: latin1
Client characterset: latin1
Conn. characterset: latin1
UNIX socket: /var/lib/mysql/mysql.sock
Binary data as: Hexadecimal
Uptime: 3 hours 51 min 13 sec
Threads: 4 Questions: 239 Slow queries: 0 Opens: 332 Flush tables: 3 Open tables: 238 Queries per second avg: 0.017
--------------
#也可以用status命令来查看
#无法在远程主机上连接当前主机的MySQL服务
[root@localhost ~]# mysql -uroot -h192.168.108.128 -p
Enter password:
ERROR 1130 (HY000): Host '192.168.108.132' is not allowed to connect to this MySQL server
创建用户:CREATE USER
bash
#格式
CREATE USER 'USERNAME'@'HOST' [IDENTIFIED BY 'password'];
#范例
create user test@'192.168.108.0/255.255.255.0' identified by '123456';
create user test2@'192.168.108.0.%' identified by'123456';
重命名用户:RENAME USER
bash
RENAME USER 'USERNAME'@'HOST' TO 'USERNAME'@'HOST';
删除用户:DROP USER
bash
DROP USER 'USERNAME'@'HOST'
#范例,删除xbq
DROP user test@'192.168.108.0/255.255.255.0'
DROP USER test2@'192.168.108.0.%';
修改密码
新版mysql中用户密码可以保存在mysql.user表的 authentication_string字段中,己经取消了password字段。
mariadb中某些版本 authentication_string,password字段共存,I日版以password字段为准,新版以authentication_string为准。
bash
#方式一
SET PASSWORD FOR 'user'@'host' = PASSWORD('password');
#mysql8.0中取消了PASSWORD方法
mysql> select PASSWORD('123456');
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('123456')' at line 1
#MariaDB中还有
#在MYSQL8.0中可以使用此写法
#MYSQL8.0中的密码是放在 mysql.user 表中 authentication_string 字段中,但MariaDB中还保留了PASSWORD字段
mysql> select Host,User,authentication_string FROM mysql.user;
+-----------+------------------+------------------------------------------------------------------------+
| Host | User | authentication_string |
+-----------+------------------+------------------------------------------------------------------------+
| localhost | mysql.infoschema | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| localhost | mysql.session | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| localhost | mysql.sys | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| localhost | root | |
+-----------+------------------+------------------------------------------------------------------------+
4 rows in set (0.00 sec)
#更新密码
mysql> set password for root@'localhost'='123456';
Query OK, 0 rows affected (0.00 sec)
mysql> select Host,User,authentication_string FROM mysql.user;
+-----------+------------------+------------------------------------------------------------------------+
| Host | User | authentication_string |
+-----------+------------------+------------------------------------------------------------------------+
| localhost | mysql.infoschema | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| localhost | mysql.session | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| localhost | mysql.sys | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| localhost | root | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 |
+-----------+------------------+------------------------------------------------------------------------+
4 rows in set (0.00 sec)
mysql>
#方式二
语法:ALTER USER test@'%' IDENTIFIED BY '123456';
#此方法通用
mysql> ALTER USER root@'localhost' IDENTIFIED BY '123456';
Query OK, 0 rows affected (0.00 sec)
#测试
[root@localhost ~]# mysql -uroot -p123456
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 16
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
#方法三
[root@localhost ~]# mysqladmin -uroot -p123456 password abcde
mysqladmin: [Warning] Using a password on the command line interface can be insecure.
Warning: Since password will be sent to server in plain text, use ssl connection to ensure password safety.
[root@localhost ~]# mysql -uroot -pabcde
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 19
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
忘记密码
bash
#方式一,保留原有数据
#1 启动时添加指定项
--skip-grant-tables
--skip-networking
#2 使用UPDATE命令修改管理员密码
#3 移除配置项重启
#方式二范例
[root@localhost ~]# vim /etc/my.cnf.d/mysql-server.cnf
[mysqld]
skip-grant-tables
skip-networking #MYSQL8.0不需要
[root@localhost ~]# systemctl restart mysqld.service
#直接跳过密码
[root@localhost ~]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 7
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
#步骤1
mysql> update mysql.user set authentication_string='' where user='root' and host='localhost';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
#步骤2
mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)
#再执行下面命令
mysql> alter user root@'localhost' identified by 'xiaomi';
Query OK, 0 rows affected (0.00 sec)
[root@localhost ~]# vim /etc/my.cnf.d/mysql-server.cnf
[mysqld]
#pid-file=/run/mysqld/mysqld.pid
#skip-grant-tables
[root@localhost ~]# mysql -uroot -pxiaomi
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 9
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
配置项 作用说明 适用场景 注意事项 skip-grant-tables跳过 MySQL 的权限验证系统,任何用户无需密码即可登录数据库,且拥有所有操作权限 忘记 root 密码时重置密码;紧急修复权限表损坏的情况 极度危险!启用后数据库完全暴露,仅临时使用,操作完成后立即关闭并重启 MySQL skip-networking禁止 MySQL 监听网络连接,只能通过本地 Unix 套接字(Linux)或命名管道(Windows)连接数据库 仅允许本地管理数据库,防止远程连接带来的安全风险;减少网络层攻击面 启用后无法远程连接数据库(如通过 Navicat、Python 脚本等),需远程访问时必须关闭此配置 使用提示:
- 修改配置后需重启 MySQL 服务才能生效。
- 若同时启用这两个配置,意味着:
- 只能在服务器本地登录 MySQL
- 登录时无需验证密码
- 完成操作(如重置密码)后,务必删除这两行配置并重启服务,否则会导致严重的安全漏洞。
范例:删库跑路之清空root密码方法
bash
#方式二,会清除所有数据
#停止服务
[root@localhost ~]# systemctl stop mysqld.service
#删除数据目录下所有内容
[root@localhost ~]# rm -rf /var/lib/mysql/*
#重启服务,恢复空密码登陆
[root@localhost ~]# systemctl start mysqld.service
[root@localhost ~]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
在当前MYSQL服务中添加用户
mysql
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> create user root@'192.168.108.1' identified by '123456'; #需要远程连接本mysql的客户端地址
Query OK, 0 rows affected (0.00 sec)
mysql> select Host,User from user;
+---------------+------------------+
| Host | User |
+---------------+------------------+
| 192.168.108.1 | root |
| localhost | mysql.infoschema |
| localhost | mysql.session |
| localhost | mysql.sys |
| localhost | root |
+---------------+------------------+
5 rows in set (0.00 sec)
到192.168.108.1(笔记本)操作
mysql -uroot -h192.168.108.145 -p123456

bash
#查看当前客户端连接时适用的用户名和主机
mysql> select user();
+--------------------+
| user() |
+--------------------+
| root@192.168.108.1 |
+--------------------+
1 row in set (0.00 sec)
#查看线程
mysql> show processlist;
+----+------+---------------------+-------+---------+------+-------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+------+---------------------+-------+---------+------+-------+------------------+
| 11 | root | localhost | mysql | Sleep | 360 | | NULL |
| 14 | root | 192.168.108.1:63707 | NULL | Query | 0 | init | show processlist |
+----+------+---------------------+-------+---------+------+-------+------------------+
2 rows in set (0.00 sec)
#查看数据库
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
+--------------------+
1 row in set (0.00 sec)
#没有权限
mysql> use msyql;
ERROR 1044 (42000): Access denied for user 'root'@'192.168.108.1' to database 'msyql'
mysql> create database db1;
ERROR 1044 (42000): Access denied for user 'root'@'192.168.108.1' to database 'db1'
3.9权限管理和DCL语句
在MySQL服务中,新创建的用户仅仅只能连接,没有操作权限,需要配置相应的权限后才能使用。
3.9.1 权限类别
管理类
CREATE USER,FILE,SUPER,SHOW DATABASES,RELOAD,SHUTDOWN,REPLICATION SLAVE,REPLICATION CLIENT,LOCK TABLES,PROCESS,CREATE TEMPORARY TABLES
程序类针对FUNCTION、PROCEDURE、TRIGGER
CREATE,ALTER,DROP,EXCUTE
库和表级别针对DATABASE、TABLE
ALTER,CREATE,CREATE VIEW,DROP INDEX,SHOW VIEW,WITH GRANT OPTION(将自己获得的权限转赠给其他用户)
数据操作
SELECT,INSERT,DELETE,UPDATE
字段级别
SELECT(col1,coI2.,...),UPDATE(col1,col2,...),INSERT(col1,col2,...)
所有权限
ALL PRIVILEGES或ALL
3.9.2 授权
格式
bash
mysql> help grant
Name: 'GRANT'
Description:
Syntax:
GRANT
priv_type [(column_list)]
[, priv_type [(column_list)]] ...
ON [object_type] priv_level
TO user_or_role [, user_or_role] ...
[WITH GRANT OPTION]
[AS user
[WITH ROLE
DEFAULT
| NONE
| ALL
| ALL EXCEPT role [, role ] ...
| role [, role ] ...
#priv_type 要授予的权限ALL [PRIVILEGES]
#object_type 对象的类型TABLE|FUNCTION|PROCEDURE
#priv_level 范围 *|*.*|db_name.*|db_name.tbl_name|tbl_name|db_name.routine_name(指定库的函数,存储过程,触发器)
#with_option 选项
#GRANT OPTION 可以将自己的权限授权给其它账号
#MAX_QUERIES_PER_HOUR N 每小时最大查询次数
#MAX_UPDATES_PER_HOUR N 每小时最大更新次数
#MAX_CONNECTIONS_PER_HOUR N 每小时最大连接次数
#MAX_USER_CONNECTIONS N 最大用户连接数
#MAX_USER_CONNECTIONS 指的是瞬间的并发连接数,而MAX_CONNECTIONS_PER_HOUR指的是每小时累计的最大连接次数
#资源限制是对某一账号进行累计的,而不是对账号的一次连接进行累计的,当资源限制到达后,账号的任何一次相关操作都会被拒
范例:
bash
#只能查询,插入指定字段
GRANT SELECT(col1),INSERT(col1,col2) ON mydb.mytbl TO 'someuser'@'somehost';
#有指定库的所有权限
GRANT ALL ON wordpress.* TO wordpress@'10.0.0.%';
#授予所有权限
GRANT ALL PRIVILEGES ON *.* TO 'root'@'10.0.0.%' WITH GRANT OPTION;
#创建用户和授权同时执行的方式在MySQL8.0取消了
GRANT ALL ON wordpress.* TO wordpress@'192.168.108.%' IDENTIFIED BY 'huawei';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.108.%' IDENTIFIED BY 'huawei' WITH GRANT OPTION;
3.9.3 取消权限
格式
bash
REVOKE
priv_type [(column_list)]
[, priv_type [(column_list)]] ...
ON [object_type] priv_level
FROM user_or_role [, user_or_role] ...
范例
bash
REVOKE DELETE ON *.* FROM 'testuser'@'172.16.0.%';
REVOKE ALL ON *.* FROM'testuser'@'172.16.0.%';
3.9.4查看用户权限
格式
mysql
#查看指定用户权限
SHOW GRANTS FOR 'user'@'host';
#查看当前使用中的用户的权限
SHOW GRANTS FOR CURRENT_USER[()];
SHOW GRANTS FOR CURRENT_USER;
注意
- MariaDB服务进程启动时会读取mysql库中所有授权表至内存。
- GRANT或REVOKE等执行权限操作会保存于系统表中,MariaDB的服务进程通常会自动重读授权表,使之生效。
- 对于不能够或不能及时重读授权表的命令,可手动让MariaDB的服务进程重读授权表:mysql>FLUSH PRIVILEGES。
范例
bash
#本地操作
#创建用户
mysql> create user 'root'@'192.168.108.%' identified by '123456';
Query OK, 0 rows affected (0.01 sec)
mysql> select host,user from mysql.user;
+---------------+------------------+
| host | user |
+---------------+------------------+
| 192.168.108.% | root |
| localhost | mysql.infoschema |
| localhost | mysql.session |
| localhost | mysql.sys |
| localhost | root |
+---------------+------------------+
5 rows in set (0.00 sec)
#查看新用户的权限,默认只有 USAGE 权限,只能连接
mysql> show grants for 'root'@'192.168.108.%';
+----------------------------------------------+
| Grants for root@192.168.108.% |
+----------------------------------------------+
| GRANT USAGE ON *.* TO `root`@`192.168.108.%` |
+----------------------------------------------+
1 row in set (0.00 sec)
#远程连接,远程操作
[root@localhost ~]# mysql -uroot -p123456 -h192.168.108.128
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 14
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
#查看权限,远程操作
mysql> SHOW GRANTS FOR CURRENT_USER;
+----------------------------------------------+
| Grants for root@192.168.108.% |
+----------------------------------------------+
| GRANT USAGE ON *.* TO `root`@`192.168.108.%` |
+----------------------------------------------+
1 row in set (0.00 sec)
#无权限创建,远程操作
mysql> create database db1;
ERROR 1044 (42000): Access denied for user 'root'@'192.168.108.%' to database 'db1'
bash
#本地操作
mysql> create database db1;
mysql> create database db2;
mysql> use db1;
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;
mysql> insert student (name,age)values('xiaoming',20);
#授权能查看 mysql 中的 user 表,本地操作
mysql> grant select on db1.student to root@'192.168.108.%';
Query OK, 0 rows affected (0.00 sec)
#远程用户再次刷新,远程操作
mysql> SHOW GRANTS FOR CURRENT_USER;
+-----------------------------------------------------------+
| Grants for root@192.168.108.% |
+-----------------------------------------------------------+
| GRANT USAGE ON *.* TO `root`@`192.168.108.%` |
| GRANT SELECT ON `db1`.`student` TO `root`@`192.168.108.%` |
+-----------------------------------------------------------+
2 rows in set (0.00 sec)
#能看到数据库,远程操作
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| db1 |
| information_schema |
+--------------------+
2 rows in set (0.00 sec)
#远程操作
mysql> use db1;
Database changed
mysql> show tables;
+---------------+
| Tables_in_db1 |
+---------------+
| student |
+---------------+
1 row in set (0.00 sec)
#远程操作
mysql> select * from student;
+----+----------+------+--------+
| id | name | age | gender |
+----+----------+------+--------+
| 10 | xiaoming | 20 | M |
+----+----------+------+--------+
1 row in set (0.00 sec)
#没有更新权限,远程操作
mysql> update student set age=25 where id=10;
ERROR 1142 (42000): UPDATE command denied to user 'root'@'192.168.108.1' for table 'student'
#没有删除权限,远程操作
mysql> delete from student where id=10;
ERROR 1142 (42000): DELETE command denied to user 'root'@'192.168.108.1' for table 'student'
#继续授权,本地操作
mysql> grant update,delete on db1.student to root@'192.168.108.%';
#再次查看,远程操作
mysql> SHOW GRANTS FOR CURRENT_USER;
+---------------------------------------------------------------------------+
| Grants for root@192.168.108.% |
+---------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `root`@`192.168.108.%` |
| GRANT SELECT, UPDATE, DELETE ON `db1`.`student` TO `root`@`192.168.108.%` |
+---------------------------------------------------------------------------+
2 rows in set (0.00 sec)
#测试,远程操作
mysql> update student set age=25 where id=10;
mysql> select * from student;
+----+----------+------+--------+
| id | name | age | gender |
+----+----------+------+--------+
| 10 | xiaoming | 25 | M |
+----+----------+------+--------+
1 row in set (0.00 sec)
mysql> delete from student where id=10;
mysql> select * from student;
Empty set (0.00 sec)
范例
bash
#创建数据库,本地操作
mysql> create database eshop;
Query OK, 1 row affected (0.00 sec)
#创建用户,本地操作
mysql> create user eshoper@'192.168.108.%' identified by '123456';
Query OK, 0 rows affected (0.00 sec)
#授权,本地操作
mysql> grant all on eshop.* to eshoper@'192.168.108.%';
Query OK, 0 rows affected (0.00 sec)
#远程测试
C:\Users\69466>mysql -ueshoper -p123456 -h192.168.108.128
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 17
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2025, 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> show databases;
+--------------------+
| Database |
+--------------------+
| eshop |
| information_schema |
+--------------------+
2 rows in set (0.00 sec)
#创建表
mysql> use eshop;
Database changed
mysql> create table product (id int,name varchar(10));
Query OK, 0 rows affected (0.10 sec)
mysql> show tables;
+-----------------+
| Tables_in_eshop |
+-----------------+
| product |
+-----------------+
1 row in set (0.00 sec)
3.10MySQL图形化远程管理工具
在MySQL数据库中创建用户并授权后,可以使用相关图形化工具进行远程的管理。
常见的图形化管理工具包括Navicat,SQLyog,DBbear等。
3.10.1 Navicat 工具
3.10.2 SQLyog 工具

3.11实现基于LAMP架构的开源网站
3.11.1 LAMP 架构说明
LAMP是指一组通常一起使用来运行动态网站的自由软件名称首字母的缩写。
- L是指Linux操作系统。
- A是指Apache,用来提供Web服务。
- M指MySQL,用来提供数据库服务。
- P指PHP,是动态网站的的一种开发语言。
LAMP是中小型动态网站的常见组合,虽然这些开放源代码程序本身并不是专门设计成同另几个程序一起工作的,但由于它们各自的特点和普遍性,使得这个组合在搭建动态网站这一领域开始流行起来。
3.11.2 PHP 简介
PHP:(Hypertext Preprocessor)超文本预处理器。
PHP是通用服务器端脚本编程语言,主要用于WEB开发实现动态WEB页面,也是最早实现将脚本嵌入HTML源码文档中的服务器端脚本语言之一。同时,PHP还提供了一个命令行接口,因此,其也可以在大多数系统上作为一个独立的SHELL来使用。Rasmus Lerdorf于1994年开始开发PHP,最初是一组被Rasmus Lerdorf称作"Personal Home PageTool"的Perl脚本,可以用于显示作者的简历并记录用户对其网站的访问。后来,Rasmus Lerdorf使用C语言将这些Perl脚本重写为CGI程序,还为其增加了运行Web forms的能力以及与数据库交互的特性,并将其重命名为"Personal Home Page/Forms Interpreter"或"PHP/FI"。此时,PHP/FI已经可以用于开发简单的动态WEB程序了,这即PHP1.0。1995年6月,Rasmus Lerdorf 把它的 PHP发布于comp.infosystems.www.authoring.cgi Usenet讨论组,从此PHP开始走进人们的视野。1997年,其2.0版本发布。
1997年,两名以色列程序员Zeev Suraski 和Andi Gutmans重写的PHP的分析器(parser)成为 PHP发展到3.0的基础,而且从此将PHP重命名为PHP:Hypertext Preprocessor。此后,这两名程序员开始重写整个PHP核心,并于1999年发布了Zend Engine1.0,这也意味着PHP 4.0的诞生。2004年7月,ZendEngine 2.0发布,由此也将PHP带入了PHP5时代。PHP5包含了许多重要的新特性,如增强的面向对象编程的支持、支持PDO(PHP Data Objects)扩展机制以及一系列对PHP性能的改进。
Zend Engine是开源的、PHP脚本语言的解释器,它最早是由以色列理工学院(Technion)的学生AndiGutmans和Zeev Suraski 所开发,Zend也正是此二人名字的合称。后来两人联合创立了ZendTechnologies公司。
Zend Engine1.0于1999年随PHP4发布,由C语言开发且经过高度优化,并能够做为PHP的后端模块使用。Zend Engine为PHP提供了内存和资源管理的功能以及其它的一些标准服务,其高性能、可靠性和可扩展性在促进PHP成为一种流行的语言方面发挥了重要作用。Zend Engine的出现将PHP代码的处理过程分成了两个阶段:首先是分析PHP代码并将其转换为称作Zend opcode的二进制格式opcode(类似Java的字节码),并将其存储于内存中;第二阶段是使用ZendEngine去执行这些转换后的Opcode。
PHP各种版本官方支持时间
https://www.php.net/supported-versions.php

/etc/php.ini配置文件格式
bash
[foo]: Section Header
directive = value
php.ini 配置参考文档
bash
php.ini的核心配置选项文档 http://php.net/manual/zh/ini.core.php
php.ini配置选项列表 http://php.net/manual/zh/ini.1ist.php
php常见配置项
bash
expose_php=On #响应报文显示首部字段x-powered-by:PHP/x.y.z,暴露php版本,建议为off
max_execution_time=30 #最长执行时间30s
memory_limit=128M #生产不够,可调大
display_errors=off #调试使用,不要打开,否则可能暴露重要信息
display_startup_errors=off #建议关闭
post_max_size=8M #最大上传数据大小,生产可能调大,比下面项大
upload_max_filesize=2M #最大上传文件,生产可能要调大
max_file_uploads=20 #同时上传最多文件数
date.timezone=Asia/shanghai #指定时区
short_open_tag=On #支持短标签
3.11.3实现博客项目
服务器配置
| ip | 作用 | 软件 |
|---|---|---|
| 192.168.108.100 | 提供WEB服务,PHP动态解析 | Apache,PHP |
| 192.168.108.101 | 提供数据库服务 | MySQL |
WordPress
WordPress是使用PHP语言开发的博客平台,用户可以在支持PHP和MySQL数据库的服务器上架设属于自己的网站。也可以把WordPress当作一个内容管理系统(CMS)来使用。
官方网站
具体实现
bash
#在100上安装apapche和PHP
[root@web ~]# yum -y install httpd php php-mysqlnd php-json php-gd php-xml php-mbstring php-zip
[root@web ~]# php -v
PHP 7.2.24 (cli) (built: Oct 22 2019 08:28:36) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
#关闭防火墙
[root@web ~]# systemctl disable --now firewalld
#启动WEB服务
[root@web ~]# systemctl start httpd.service
#添加php测试页面
[root@web ~]# vim /var/www/html/test.php
<?php
phpinfo();
通过浏览器访问网站结果:

bash
#下载wordpress 源码
[root@web ~]# cd /var/www/html/
[root@web html]# wget https://cn.wordpress.org/latest-zh_CN.zip
[root@web html]# unzip latest-zh_CN.zip
[root@web html]# ls
latest-zh_CN.zip test.php wordpress
#修改属主属组
[root@web html]# chown -R apache.apache wordpress/
#创建数据库
[root@mysql ~]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.26 Source distribution
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> create database wordpress;
Query OK, 1 row affected (0.02 sec)
#创建用户
mysql> create user 'wordpresser'@'192.168.108.%' identified by '123456';
Query OK, 0 rows affected (0.02 sec)
#授权
mysql> grant all on wordpress.* to'wordpresser'@'192.168.108.%';
Query OK, 0 rows affected (0.01 sec)
为项目配置域名
bash
#在web服务器上配置域名指向的目录
[root@web ~]# vim /etc/httpd/conf.d/blog.xbq.cloud.conf
<VirtualHost *:80>
ServerName blog.xbq.cloud
DocumentRoot "/var/www/html/wordpress"
<Directory "/var/www/html/wordpress">
AllowOverride all
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
#重启httpd
[root@web ~]# systemctl restart httpd
#在物理机上为域名设置解析
#在C:\windows\System32\drivers\etc\hosts添中如下行
192.168.108.100 blog.xbq.cloud
在页面上填写相关配置
浏览器访问页面:http://blog.xbq.cloud
现在就开始!
填写配置:
- 数据库名:wordpress
- 用户名:wordpresser
- 密码:123456
- 数据库主机:192.168.108.101
- 点击提交
运行安装程序
- 站点标题:mysql
- 用户名:admin
- 密码:huawei
- 确认密码:勾选
- 邮箱:xxxxxxxx@qq.com
- 点击安装
最后:输入用户名(邮箱地址)和密码,点击登录。
成功进入WordPress页面!!!
完成配置后,可通过浏览器域名解析访问。