MySQL SQL语句

SQL语句

SQL语句有多种类型:

  1. 数据查询语言(DQL)
    数据查询语言(Data Query Language, DQL)是SQL语言中,负责进行数据查询而不会对数据本身进行修改的语句,这是最基本的SQL语句。SELECT是DQL(也是所有SQL)用得最多的动词,其他DQL常用的保留字有FROM,WHERE,GROUP BY,HAVING和ORDER BY。这些DQL保留字常与其他类型的SQL语句一起使用。

  2. 数据定义语言(DDL)
    数据定义语言 (Data Definition Language, DDL) 是SQL语言集中,负责数据结构定义与数据库对象定义的语言,由CREATE、ALTER与DROP三个语法所组成。

  3. 数据操纵语言(DML)
    数据操纵语言(Data Manipulation Language, DML)是SQL语言中,负责对数据库对象运行数据访问工作的指令集,以INSERT、UPDATE、DELETE三种指令为核心,分别代表插入、更新与删除。

  4. 数据控制语言(DCL)
    数据控制语言 (Data Control Language) 在SQL语言中,是一种可对数据访问权进行控制的指令,它可以控制特定用户账户对数据表、查看表、预存程序、用户自定义函数等数据库对象的控制权。由GRANT和REVOKE两个指令组成。DCL以控制用户的访问权限为主,GRANT为授权语句,对应的REVOKE是撤销授权语句。

  5. 指针控制语言(CCL)
    它的语句,像DECLARE CURSOR,FETCH INTO和UPDATE WHERE CURRENT用于对一个或多个表单独行的操作。

  6. 事务处理语言(TPL)
    它的语句能确保被DML语句影响的表的所有行及时得以更新。TPL语句包括BEGIN TRANSACTION,COMMIT和ROLLBACK。

1、DDL操作

1.1 数据库DDL操作

//创建数据库
//语法:CREATE DATABASE [IF NOT EXISTS] 'DB_NAME';

//创建数据库hzz
mysql> CREATE DATABASE IF NOT EXISTS hzz;
Query OK, 1 row affected (0.00 sec)

//查看当前实例有哪些数据库
mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| hzz	             |
+--------------------+
5 rows in set (0.00 sec)

//删除数据库
//语法:DROP DATABASE [IF EXISTS] 'DB_NAME';

//删除数据库hzz
mysql> DROP DATABASE IF EXISTS hzz;
Query OK, 0 rows affected (0.00 sec)

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

//创建数据库时,设置数据库的字符集:
//CHARACTER SET:指定数据库采用的字符集,utf8不能写成utf-8,建议使用utf8mb4字符集
//COLLATE:指定数据库字符集的排序规则,utf8mb4的默认排序规则为utf8mb4_general_ci(通过show character set查看)
mysql> CREATE DATABASE dbtest CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

//数据库客户端字符编码需要和服务端字符集保持一致
//SET NAMES:指定客户端字符集
mysql> SET NAMES utf8mb4;

//字符集配置都可写入MySQL配置文件中启动MySQL服务时自动加载

1.2 表DDL操作

//创建表
//语法:CREATE TABLE table_name (col1 datatype 修饰符,col2 datatype 修饰符) ENGINE='存储引擎类型';

//在数据库hzz里创建表hzztable
mysql> CREATE DATABASE hzz;      	//创建数据库hzz
Query OK, 1 row affected (0.00 sec)

mysql> use hzz;      			//进入hzz数据库
Database changed

//创建hzztable表
mysql> CREATE TABLE hzztable (id int(10) NOT NULL,name VARCHAR(100) NOT NULL,age tinyint);
Query OK, 0 rows affected (0.09 sec)

//查看当前数据库有哪些表
mysql> SHOW TABLES;
+----------------------+
| Tables_in_hzz |
+----------------------+
| hzztable             |
+----------------------+
1 row in set (0.00 sec)

//删除表
//语法:DROP TABLE [ IF EXISTS ] 'table_name';

//删除表hzztable
mysql> DROP TABLE hzztable;
Query OK, 0 rows affected (0.01 sec)

mysql> SHOW TABLES;
Empty set (0.00 sec)

//创建表时,设置字段、表的字符编码
mysql> CREATE TABLE tbtest(id int(10),user_name varchar(60) CHARACTER SET GBK COLLATE gbk_chinese_ci,email varchar(60))CHARACTER SET utf8mb4 COLLATE utf8_general_ci;

1.3 用户DDL操作

MySQL用户帐号由两部分组成,如'USERNAME'@'HOST',表示此USERNAME只能从此HOST上远程登录;HOST用于限制此用户可通过哪些主机远程连接mysql程序。

HOST的值可为:

  • IP地址,如:172.16.12.129
  • 通配符
    • %:匹配任意长度的任意字符,常用于设置允许从任何主机登录
    • _:匹配任意单个字符
//数据库用户创建
//语法:CREATE USER 'username'@'host' [IDENTIFIED BY 'password'];

//创建数据库用户hzz
mysql> CREATE USER 'hzz'@'127.0.0.1' IDENTIFIED BY 'hzz123!';
Query OK, 0 rows affected (0.00 sec)

//刷新授权表
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.006 sec)

//使用新创建的用户和密码登录
[root@localhost ~]# mysql -uhzz -phzz123! -h127.0.0.1
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 6
Server version: 5.7.23 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

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> 

//删除数据库用户
//语法:DROP USER 'username'@'host'; 

//删除数据库用户hzz
mysql> DROP USER 'hzz'@'127.0.0.1';
Query OK, 0 rows affected (0.00 sec)

//刷新授权表
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.006 sec)

1.4 查看命令SHOW

mysql> SHOW CHARACTER SET;      	//查看支持的所有字符集
+----------+---------------------------------+---------------------+--------+
| Charset  | Description                     | Default collation   | Maxlen |
+----------+---------------------------------+---------------------+--------+
| big5     | Big5 Traditional Chinese        | big5_chinese_ci     |      2 |
| dec8     | DEC West European               | dec8_swedish_ci     |      1 |
| cp850    | DOS West European               | cp850_general_ci    |      1 |
| hp8      | HP West European                | hp8_english_ci      |      1 |
| koi8r    | KOI8-R Relcom Russian           | koi8r_general_ci    |      1 |
| latin1   | cp1252 West European            | latin1_swedish_ci   |      1 | 
......
......

mysql> SHOW VARIABLES LIKE '%char%';	//查看客户端的字符编码
.....
.....

mysql> SELECT CHARSET(email) FROM tbtest;	//查看某表中某字段使用的字符编码
.....
.....

mysql> SHOW ENGINES;        		//查看当前数据库支持的所有存储引擎
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| Engine             | Support | Comment
                 | Transactions | XA   | Savepoints |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
| InnoDB             | DEFAULT | Supports transactions, row-level locking, and
foreign keys     | YES          | YES  | YES        |
| MRG_MYISAM         | YES     | Collection of identical MyISAM tables
                 | NO           | NO   | NO         |
| MEMORY             | YES     | Hash based, stored in memory, useful for temporary tables      | NO           | NO   | NO         |
| BLACKHOLE          | YES     | /dev/null storage engine (anything you write to it disappears) | NO           | NO   | NO         |
| MyISAM             | YES     | MyISAM storage engine                                          | NO           | NO   | NO         |
| CSV                | YES     | CSV storage engine                                            | NO           | NO   | NO         |
| ARCHIVE            | YES     | Archive storage engine                                        | NO           | NO   | NO         |
| PERFORMANCE_SCHEMA | YES     | Performance Schema                                            | NO           | NO   | NO         |
| FEDERATED          | NO      | Federated MySQL storage engine                                | NULL         | NULL | NULL       |
+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+
9 rows in set (0.00 sec)

mysql> SHOW DATABASES;          	//查看数据库信息
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| hzz                |
+--------------------+
5 rows in set (0.00 sec)

mysql> SHOW TABLES FROM hzz;         	//不进入某数据库而列出其包含的所有表
+----------------------+
| Tables_in_hzz        |
+----------------------+
| hzztable             |
+----------------------+
1 row in set (0.00 sec)

//查看表结构
//语法:DESC [db_name.]table_name;

mysql> DESC hzz.hzztable;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | int(11)      | NO   |     | NULL    |       |
| name  | varchar(100) | NO   |     | NULL    |       |
| age   | tinyint(4)   | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
3 rows in set (0.03 sec)

//查看某表的创建命令,可以看到创建表时设置的参数
//语法:SHOW CREATE TABLE table_name;

mysql> SHOW CREATE TABLE hzz.hzztable;
+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                                                              |
+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| hzztable | CREATE TABLE `hzz` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `age` tinyint(4) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

//查看某表的状态
//语法:SHOW TABLE STATUS LIKE 'table_name'\G

mysql> use hzz;      //进入数据库hzz
Database changed
mysql> SHOW TABLE STATUS LIKE 'hzztable'\G      //查看hzztable表的状态
*************************** 1. row ***************************
           Name: hzztable
         Engine: InnoDB
        Version: 10
     Row_format: Dynamic
           Rows: 0
 Avg_row_length: 0
    Data_length: 16384
Max_data_length: 0
   Index_length: 0
      Data_free: 0
 Auto_increment: NULL
    Create_time: 2018-08-13 00:53:21
    Update_time: NULL
     Check_time: NULL
      Collation: latin1_swedish_ci
       Checksum: NULL
 Create_options:
        Comment:
1 row in set (0.00 sec)

1.5 ALTER修改操作

//修改数据库属性
//语法:ALTER DATABASE 'DB_NAME' CHARACTER SET charset_name | COLLATE collation_name

//修改数据库字符集为utf8
mysql> ALTER DATABASE hzz CHARACTER SET utf8;
Query OK, 1 row affected (0.000 sec)

//修改表
//语法:ALTER TABLE <table_name> [option]

//给hzztable表添加新的一列,先查看表结构
mysql> DESC hzztable;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(7)      | NO   |     | NULL    |       |
| name  | varchar(20) | NO   |     | NULL    |       |
| age   | tinyint(4)  | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.001 sec)

//给hzztable表添加一列'phone'
mysql> ALTER TABLE hzztable ADD phone int(11);
Query OK, 0 rows affected (0.001 sec)
Records: 0  Duplicates: 0  Warnings: 0

//查看表结构
mysql> DESC hzztable;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(7)      | NO   |     | NULL    |       |
| name  | varchar(20) | NO   |     | NULL    |       |
| age   | tinyint(4)  | YES  |     | NULL    |       |
| phone | int(11)     | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
4 rows in set (0.000 sec)

//修改hzztable表中'phone'列为'sex'
mysql> ALTER TABLE hzztable CHANGE phone sex varchar(4);
Query OK, 0 rows affected (0.005 sec)              
Records: 0  Duplicates: 0  Warnings: 0

mysql> DESC hzztable;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(7)      | NO   |     | NULL    |       |
| name  | varchar(20) | NO   |     | NULL    |       |
| age   | tinyint(4)  | YES  |     | NULL    |       |
| sex   | varchar(4)  | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
4 rows in set (0.001 sec)

//修改表名为zzhtable
mysql> ALTER TABLE hzztable RENAME TO zzhtable;
Query OK, 0 rows affected (0.002 sec)

mysql> SHOW TABLES;
+---------------+
| Tables_in_hzz |
+---------------+
| zzhtable      |
+---------------+
1 row in set (0.000 sec)

//修改数据库字符编码
mysql> ALTER DATABASE dbtest CHARACTER SET utf8 COLLATE utf8_general_ci;

//修改表字符编码
mysql> ALTER TABLE tbtest CHARACTER SET utf8 COLLATE utf8_general_ci;

1.6 获取帮助

//获取命令使用帮助
//语法:HELP commond;

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
 ......
 ......

2、DML操作

DML操作包括增(INSERT)、删(DELETE)、改(UPDATE)、查(SELECT),均属针对表的操作。

2.1 INSERT语句

//DML操作之增操作insert
//语法:INSERT [INTO] table_name [(column_name,...)] {VALUES | VALUE} (value1,...),(...),...

mysql> use hzz;
Database changed

//一次插入一条记录
mysql> INSERT INTO hzztable (id,name,age) VALUE (1,'tom',20);       
Query OK, 1 row affected (0.01 sec)

//一次插入多条记录
mysql> INSERT INTO hzztable (id,name,age) VALUES (2,'jerry',23),(3,'hzz',25),(4,'sean',28),(5,'zhangshan',26),(6,'zhangshan',20),(7,'lisi',NULL);
Query OK, 4 rows affected (0.01 sec)
Records: 4  Duplicates: 0  Warnings: 0

2.2 SELECT语句(DQL)

字段column匹配方式:

表示符含义
*所有字段
as字段别名,如col1 AS alias1
当表名很长时用别名代替

条件判断语句WHERE:

操作类型常用操作符
操作符>,<,>=,<=,=,!=
BETWEEN column# AND column#
LIKE:模糊匹配
RLIKE:基于正则表达式进行模式匹配
IS NOT NULL:非空
IS NULL:空
条件逻辑操作AND
OR
NOT
//DML操作之查操作select
//语法:SELECT column1,column2,... FROM table_name [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];

mysql> use hzz;
Database changed

mysql> select * from hzztable;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | tom       |   20 |
|  2 | jerry     |   23 |
|  3 | hzz       |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
|  7 | lisi      | NULL |
+----+-----------+------+
7 rows in set (0.00 sec)

mysql> SELECT name FROM hzztable;
+-----------+
| name      |
+-----------+
| tom       |
| jerry     |
| hzz       |
| sean      |
| zhangshan |
| zhangshan |
| lisi      |
+-----------+
7 rows in set (0.01 sec)

mysql> SELECT * FROM hzztable WHERE age >= 25;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  3 | hzz       |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
+----+-----------+------+
3 rows in set (0.00 sec)

mysql> SELECT * FROM hzztable WHERE age >= 25 AND name = 'zhangshan';
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  5 | zhangshan |   26 |
+----+-----------+------+
1 row in set (0.00 sec)

mysql> SELECT * FROM hzztable WHERE age BETWEEN 23 and 28;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  2 | jerry     |   23 |
|  3 | hzz       |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
+----+-----------+------+
4 rows in set (0.00 sec)

mysql> select * from hzztable where age is not null;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | tom       |   20 |
|  2 | jerry     |   23 |
|  3 | hzz       |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
+----+-----------+------+
6 rows in set (0.00 sec)

mysql> select * from hzztable where age is null;
+----+------+------+
| id | name | age  |
+----+------+------+
|  7 | lisi | NULL |
+----+------+------+
1 row in set (0.00 sec)

mysql> select * from hzztable where name like '%z%';
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  3 | hzz       |   25 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
+----+-----------+------+
3 rows in set (0.00 sec)

GROUP BY 分组聚合函数

group by 分组功能原理:
1.按照group by指定的列进⾏排序;
2.然后根据group by指定的列去重复,也就是将相同的值分成一组;
3.最后通过聚合函数将其他列的结果进⾏聚合。

  • 聚合函数
count() 统计数量
sum() 求和
avg() 平均数
max() 最⼤值
min() 最⼩值
group_concat() 列转⾏
//首先以name字段进行分组,然后对该字段进行排序、去重,最后通过count()聚合函数将name字段对应的age字段的数量统计出来
mysql> select name,count(age) from hzztable group by name;
+-----------+-------------+
| name      | count(age)  |
+-----------+-------------+
| hzz       |      1      |
| jerry     |      1      |
| sean      |      1      |
| tom       |      1      |
| zhangshan |      2      |
+----+-----------+--------+
5 rows in set (0.00 sec)
  • GROUP BY 分组聚合函数流程图

GROUP BY 分组聚合函数流程图

HAVING 聚合判断

HAVING:聚合判断,主要应⽤在GROUP BY之后再次进行判断。

select name,count(age) from hzztable group by name having count(age)>=2;
+-----------+-------------+
| name      | count(age)  |
+-----------+-------------+
| zhangshan |      2      |
+----+-----------+--------+

ORDER BY 聚合排序

ORDER BY:聚合排序,默认为升序(ASC),也可降序(DESC)。

ORDER BY语句含义
ORDER BY ‘column_name'根据column_name进行升序排序
ORDER BY 'column_name' DESC根据column_name进行降序排序
mysql> SELECT * FROM hzztable ORDER BY age;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  7 | lisi      | NULL |
|  1 | tom       |   20 |
|  6 | zhangshan |   20 |
|  2 | jerry     |   23 |
|  3 | hzz       |   25 |
|  5 | zhangshan |   26 |
|  4 | sean      |   28 |
+----+-----------+------+
7 rows in set (0.00 sec)

mysql> SELECT * FROM hzztable ORDER BY age DESC;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  3 | hzz       |   25 |
|  2 | jerry     |   23 |
|  1 | tom       |   20 |
|  6 | zhangshan |   20 |
|  7 | lisi      | NULL |
+----+-----------+------+
7 rows in set (0.00 sec)

LIMIT 分⻚查询

LIMIT:分⻚查询,主要对数据进行分页,查询想要的内容。

LIMIT语句含义
ORDER BY ’column_name' LIMIT 2根据column_name进行升序排序并只取前2个结果
ORDER BY ‘column_name' LIMIT 1,2根据column_name进行升序排序并且略过第1个结果取后面的2个结果
mysql> SELECT * FROM hzztable ORDER BY age limit 2;
+----+------+------+
| id | name | age  |
+----+------+------+
|  7 | lisi | NULL |
|  1 | tom  |   20 |
+----+------+------+
2 rows in set (0.00 sec)

mysql> SELECT * FROM hzztable ORDER BY age limit 1,2;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | tom       |   20 |
|  6 | zhangshan |   20 |
+----+-----------+------+
2 rows in set (0.00 sec)

2.3 update语句

//DML操作之改操作update
//语法:UPDATE table_name SET column1 = new_value1[,column2 = new_value2,...] [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];

mysql> select * from hzztable;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | tom       |   20 |
|  2 | jerry     |   23 |
|  3 | hzz       |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
|  7 | lisi      | NULL |
+----+-----------+------+
7 rows in set (0.00 sec)

mysql> update hzztable set age = 30 where name = 'lisi';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from hzztable where name = 'lisi';
+----+------+------+
| id | name | age  |
+----+------+------+
|  7 | lisi |   30 |
+----+------+------+
1 row in set (0.00 sec)

2.4 delete语句

//DML操作之删操作delete
//语法:DELETE FROM table_name [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];

mysql> select * from hzztable;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | tom       |   20 |
|  2 | jerry     |   23 |
|  3 | hzz       |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
|  7 | lisi      |   30 |
+----+-----------+------+
7 rows in set (0.00 sec)

mysql> delete from hzztable where id = 7;       //删除某条记录
Query OK, 1 row affected (0.00 sec)

mysql> select * from hzztable;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | tom       |   20 |
|  2 | jerry     |   23 |
|  3 | hzz       |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
+----+-----------+------+
6 rows in set (0.00 sec)

mysql> delete from hzztable;        //删除整张表的内容
Query OK, 6 rows affected (0.00 sec)

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

mysql> desc hzztable;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | int(11)      | NO   |     | NULL    |       |
| name  | varchar(100) | NO   |     | NULL    |       |
| age   | tinyint(4)   | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

2.5 truncate语句

truncate与delete的区别:

语句类型特点
deleteDELETE删除表内容时仅删除内容,但会保留表结构
DELETE语句每次删除一行,并在事务日志中为所删除的每行记录一项
可以通过回滚事务日志恢复数据
非常占用空间
truncate删除表中所有数据,且无法恢复
表结构、约束和索引等保持不变,新添加的行计数值重置为初始值
执行速度比DELETE快,且使用的系统和事务日志资源少
通过释放存储表数据所用的数据页来删除数据,并且只在事务日志中记录页的释放
对于有外键约束引用的表,不能使用TRUNCATE TABLE删除数据
不能用于加入了索引视图的表
//语法:TRUNCATE table_name;

mysql> select * from hzztable;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | tom       |   20 |
|  2 | jerry     |   23 |
|  3 | hzz       |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
|  7 | lisi      | NULL |
+----+-----------+------+
7 rows in set (0.00 sec)

mysql> truncate hzztable;
Query OK, 0 rows affected (0.01 sec)

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

mysql> desc hzztable;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | int(11)      | NO   |     | NULL    |       |
| name  | varchar(100) | NO   |     | NULL    |       |
| age   | tinyint(4)   | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

3、DCL操作

3.1 创建授权grant

权限类型(priv_type)

权限类型含义
ALL所有权限
SELECT读取内容的权限
INSERT插入内容的权限
UPDATE更新内容的权限
DELETE删除内容的权限
........

指定要操作的对象db_name.table_name

表示方式含义
*.*所有库的所有表
db_name指定库的所有表
db_name.table_name指定库的指定表

WITH GRANT OPTION:被授权的用户可将自己的权限副本转赠给其他用户,说白点就是将自己的权限完全复制给另一个用户。不建议使用。

//语法:GRANT priv_type,... ON [object_type] db_name.table_name TO ‘username'@'host' [IDENTIFIED BY 'password'] [WITH GRANT OPTION];

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

//授权hzz用户在数据库本机上登录访问所有数据库
mysql> GRANT ALL ON *.* TO 'hzz'@'localhost' IDENTIFIED BY 'hzz123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)

//也可表示为:
mysql> GRANT ALL ON *.* TO 'hzz'@'127.0.0.1' IDENTIFIED BY 'hzz123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)

//授权hzz用户在172.16.12.129上远程登录访问hzz数据库
mysql> GRANT ALL ON hzz.* TO 'hzz'@'172.16.12.129' IDENTIFIED BY 'hzz123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)

//授权hzz用户在所有位置上远程登录访问hzz数据库
mysql> GRANT ALL ON hzz.* TO 'hzz'@'%' IDENTIFIED BY 'hzz123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)

//刷新授权表
mysql> FLUSH PRIVILEGES;

3.2 查看授权

//查看当前登录用户的授权信息
mysql> SHOW GRANTS;
+---------------------------------------------------------------------+
| Grants for root@localhost                                           |
+---------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION |
| GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION        |
+---------------------------------------------------------------------+
2 rows in set (0.00 sec)

//查看指定用户hzz的授权信息
mysql> SHOW GRANTS FOR 'hzz'@'localhost';
+-------------------------------------------------------+
| Grants for hzz@localhost                              |
+-------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'hzz'@'localhost'      |
+-------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SHOW GRANTS FOR 'hzz'@'127.0.0.1';
+-------------------------------------------------------+
| Grants for hzz@127.0.0.1                              |
+-------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'hzz'@'127.0.0.1'      |
+-------------------------------------------------------+
1 row in set (0.00 sec)

3.3 取消授权REVOKE

//语法:REVOKE priv_type,... ON db_name.table_name FROM 'username'@'host';

mysql> REVOKE ALL ON *.* FROM 'hzz'@'172.16.12.129';
Query OK, 0 rows affected (0.00 sec)

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

注意:mysql服务进程启动时会读取mysql库中的所有授权表至内存中:

  • GRANT或REVOKE等执行权限操作会保存于表中,mysql的服务进程会自动重读授权表,并更新至内存中
  • 对于不能够或不能及时重读授权表的命令,可手动让mysql的服务进程重读授权表
mysql> FLUSH PRIVILEGES;

4、找回root密码

1.停⽌MySQL服务
[root@localhost ~]# systemctl stop mysqld

2.编辑MySQL服务配置文件,跳过授权登陆验证
[root@localhost ~]# vim /etc/my.cnf
[mysqld]
skip-grant-tables	#添加此行,表示跳过授权表

3.开启MySQL服务,免密登陆MySQL
[root@localhost ~]# systemctl start mysqld
[root@localhost ~]# mysql	#直接使用mysql命令即可登录

4.登录成功后修改MySQL密码
mysql> UPDATE mysql.user SET authentication_string=PASSWORD("123456") WHERE user='root' and host='localhost';

5.关闭MySQL服务,删除配置文件中添加的跳过授权表配置
[root@localhost ~]# systemctl stop mysqld
[root@localhost ~]# vim /etc/my.cnf
[mysqld]
skip-grant-tables	#删除该行

6.再启动MySQL服务,使⽤修改后的密码登陆
[root@localhost ~]# systemctl start mysqld
[root@localhost ~]# mysql -uroot -p123456

7.注意
跳过授权表之后,所有的本地和远程⽤户都不需要⽤户名密码认证即可连接,⾮常危险。
# MySQL  

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×