mysql基础
mysql基础
1.关系型数据库组成结构和名次解释
以表格的形式出现,每行为单独的一条记录,每列为一个单独的字段,许多的记录和字段组成一张表单,若干的表单组成库(database)
-
记录
在数据库当中,表当中的行称之为记录
-
字段
在数据库当中,表当中的列称之为字段
-
MySQL 数据类型
数据类型用于指定特定字段所包含的数据的规则,他决定了数据保存在字段里的方式,包括分配给字段的宽度,以及是否可以是数字、字母、日期和时间等。任何数据或数据的组合都有对应的数据类型,用于存储字母、数字、日期和时间、图像、二进制数据等。数据类型是数据本身的特征,其特性被设置到表的字段。
MySQL 常见的基础数据类型
* 字符串类型 CHAR(0-255固定长度) ,VARCHAR(0-255可变长度)
* 数值类型 INT(整数型) 、FLOAT (浮点型)
* 日期和时间类型 DATE(年月日) 、 TIME(时分秒)
- MySQL 约束类型
约束(constraint)是一种限制,他通过对表的行或列的数据做出限制,来确保数据的完整性、唯一性。
主键约束:一个或多个字段的组合,填入的数据必须能在本表中唯一标识本行。且必须提供数据,不能为空(NOT NULL)一个表只能存在一个
惟一键约束:一个或多个字段的组合,填入的数据必须能在本表中唯一标识本行。允许为空(NULL)一个表可以存在多个
非空约束:非空约束用于确保当前列的值不为空,非空约束只能出现在表对象的列上
外键约束:一个表中的某字段可填入数据取决于另一个表的主键已有的数据
-
MySQL 索引
将表中的一个或多个字段中的数据复制一份另存,并且这些数据需要按特定次序排序存储
-
事务(transaction)是并发控制的基本单位
可以把一系列要执行的操作称为事务,而事务管理就是管理这些操作要么完全执行,要么完全不执行
1.2 关系型数据库的常见组件
关系型数据库的常见组件有:
- 数据库:database
- 表:table,由行(row)和列(column)组成
- 索引:index
- 视图:view
- 用户:user
- 权限:privilege
- 存储过程:procedure
- 存储函数:function
- 触发器:trigger
- 事件调度器:event scheduler
1.3 SQL语句
SQL语句有三种类型:
- DDL:Data Defination Language,数据定义语言
- DML:Data Manipulation Language,数据操纵语言
- DCL:Data Control Language,数据控制语言
SQL语句类型 | 对应操作 |
---|---|
DDL | CREATE:创建 DROP:删除 ALTER:修改 |
DML | INSERT:向表中插入数据 DELETE:删除表中数据 UPDATE:更新表中数据 SELECT:查询表中数据 |
DCL | GRANT:授权 REVOKE:移除授权 |
2.mysql的安装和配置
2.1 mysql安装
- 源代码:编译安装
- 二进制格式的程序包:展开至特定路径,并经过简单配置后即可使用
- 程序包管理器管理的程序包:
- rpm:有两种
- OS Vendor:操作系统发行商提供的
- 项目官方提供的
- deb
- rpm:有两种
#配置yum源
# wget https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm
# rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm
// 查看 YUM 仓库关于 MySQL 的所有仓库列表
# yum repolist all | grep mysql
// 只查看启用的
# yum repolist enabled | grep mysql
// 选择具体的版本,用下面的工具
或是在/etc/yum.repos.d/mysql-community.repo中将5.7的修改为enable=1 , 8.0的enable=0
// 安装 YUM 管理工具包,此包提供了 yum-config-manager 命令工具
# yum install yum-utils
// 禁用 8.0
# yum-config-manager --disable mysql80-community
// 启用 5.7
# yum-config-manager --enable mysql57-community
// 再次确认启用的mysql仓库
# yum repolist enabled | grep mysql
#安装mysql5.7
yum install -y mysql-community-server mysql-community-client
2.2 mysql配置
#启动mysql并设置开机自动启动
systemctl enable --now mysqld
systemctl status mysqld
#确保3306端口已经监听起来
ss -antl
#在日志文件中找出临时密码
grep "password" /var/log/mysqld.log
#在日志文件中找出密码
[root@localhost ~]# grep 'password' /var/log/mysqld.log
2020-05-19T07:42:52.379319Z 1 [Note] A temporary password is generated for rocalhost: yveWXp%z_6AR
#取消密码复杂度
编辑 /etc/my.cnf配置文件, 在 [mysqld]配置块儿中添加如下内容
plugin-load=validate_password.so
validate-password=OFF
或是在mysql中设置密码长度和密码安全等级
mysql> set global validate_password_policy=0;
mysql> set global validate_password_length=1;
#修改mysql登录密码
mysql>alter user root@localhost identified by '123456';
#在shell中用mysqladmin来改密
shell> mysqladmin -p'现在的密码' password '更改后的密码'
2.3 破解密码
// 启动免授权服务端
# 在 /etc/my.cnf 配置文件中添加如下配置项,并重启服务
skip-grant-tables=1
# 在服务端本地执行 mysql, 通过本地连接数据库
shell> mysql
# 修改用户的密码,将root用户密码改为123456
mysql> update mysql.user set authentication_string=PASSWORD('123456') where user='root' and host='localhost';
// 再次重启服务(重启前注释或删除my.cnf中的skip-grant-tables=1)
shell> systemctl restart mysqld
//mariadb用以下方式
# mysql
MariaDB [(none)]> use mysql;
MariaDB [(none)]> UPDATE user SET password=password("New-password") WHERE user='root';
MariaDB [(none)]> flush privileges;
MariaDB [(none)]> exit;
3. mysql 程序组成
- 客户端
- mysql:CLI交互式客户端程序
- mysql_secure_installation:安全初始化,强烈建议安装完以后执行此命令
- mysqldump:mysql备份工具
- mysqladmin
- 服务器端
- mysqld
3.1 mysql工具的使用
//语法:mysql [OPTIONS] [database]
//常用的OPTIONS:
-uUSERNAME //指定用户名,默认为root
-hHOST //指定服务器主机,默认为localhost,推荐使用ip地址
-pPASSWORD //指定用户的密码
-P# //指定数据库监听的端口,这里的#需用实际的端口号代替,如-P3307
-V //查看当前使用的mysql版本
-e //不登录mysql执行sql语句后退出,常用于脚本
[root@localhost ~]# mysql -V
mysql Ver 14.14 Distrib 5.7.30, for Linux (x86_64) using EditLine wrapper
[root@localhost ~]# mysql -uroot -p123456 -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 10
Server version: 5.7.30 MySQL Community Server (GPL)
Copyright (c) 2000, 2020, 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>
//注意,不推荐直接在命令行里直接用-pPASSWORD的方式登录,而是使用-p选项,然后交互式输入密码
[root@localhost ~]# mysql -uroot -p -h127.0.0.1
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 5.7.30 MySQL Community Server (GPL)
Copyright (c) 2000, 2020, 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>
[root@localhost ~]# mysql -uroot -p -h127.0.0.1 -e 'SHOW DATABASES;'
Enter password:
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
3.2 服务器监听的两种socket
socket类型 | 说明 |
---|---|
ip socket | 默认监听在tcp的3306端口,支持远程通信 |
unix sock | 监听在sock文件上(/tmp/mysql.sock,/var/lib/mysql/mysql.sock) 仅支持本地通信 server地址只能是:localhost,127.0.0.1 |
4. mysql数据库操作
4.1 DDL操作
4.1.1 数据库操作
//创建数据库
//语法:CREATE DATABASE [IF NOT EXISTS] 'DB_NAME';
//创建数据库school
mysql> CREATE DATABASE IF NOT EXISTS school;
Query OK, 1 row affected (0.00 sec)
//查看当前有那些数据库
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| school |
| sys |
+--------------------+
5 rows in set (0.01 sec)
//删除数据库
//语法:DROP DATABASE [IF EXISTS] 'DB_NAME';
//删除数据库school
mysql> DROP DATABASE IF EXISTS school;
Query OK, 0 rows affected (0.01 sec)
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.00 sec)
4.1.2 表操作
//创建表
//语法:CREATE TABLE table_name (col1 datatype 修饰符,col2 datatype 修饰符) ENGINE='存储引擎类型';
//在数据库school里创建表school
mysql> CREATE DATABASE school;
Query OK, 1 row affected (0.00 sec)
mysql> use school;
Database changed
mysql> CREATE TABLE school (id int NOT NULL,name VARCHAR(100) NOT NULL,age tinyint);
Query OK, 0 rows affected (0.01 sec)
//查看当前数据库有哪些表
mysql> SHOW TABLES;
+------------------+
| Tables_in_school |
+------------------+
| school |
+------------------+
1 row in set (0.00 sec)
//删除表
//语法:DROP TABLE [ IF EXISTS ] 'table_name';
//删除表school
mysql> DROP TABLE school;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW TABLES;
Empty set (0.00 sec)
4.1.3 用户操作
mysql用户帐号由两部分组成,如'USERNAME'@'HOST',表示此USERNAME只能从此HOST上远程登录
这里('USERNAME'@'HOST')的HOST用于限制此用户可通过哪些主机远程连接mysql程序,其值可为:
- IP地址,如:172.16.12.129
- 通配符
- %:匹配任意长度的任意字符,常用于设置允许从任何主机登录
- _:匹配任意单个字符
//数据库用户创建
//语法:CREATE USER 'username'@'host' [IDENTIFIED BY 'password'];
//创建数据库用户tom
mysql> CREATE USER 'tom'@'127.0.0.1' IDENTIFIED BY '123456';
Query OK, 0 rows affected (0.00 sec)
//使用新创建的用户和密码登录
[root@localhost ~]# mysql -utom -p123456 -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 5
Server version: 5.7.30 MySQL Community Server (GPL)
Copyright (c) 2000, 2020, 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';
mysql> DROP USER 'tom'@'127.0.0.1';
Query OK, 0 rows affected (0.00 sec)
4.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 |
......
......
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 |
| school |
| sys |
+--------------------+
5 rows in set (0.00 sec)
mysql> SHOW TABLES FROM mysql; //不进入某数据库而列出其包含的所有表
+---------------------------+
| Tables_in_mysql |
+---------------------------+
| columns_priv |
| db |
| engine_cost |
| event |
| func |
| general_log |
| gtid_executed |
| help_category |
| help_keyword |
| help_relation |
| help_topic |
| innodb_index_stats |
| innodb_table_stats |
| ndb_binlog_index |
| plugin |
| proc |
| procs_priv |
| proxies_priv |
| server_cost |
| servers |
| slave_master_info |
| slave_relay_log_info |
| slave_worker_info |
| slow_log |
| tables_priv |
| time_zone |
| time_zone_leap_second |
| time_zone_name |
| time_zone_transition |
| time_zone_transition_type |
| user |
+---------------------------+
31 rows in set (0.00 sec)
//查看表结构
//语法:DESC [db_name.]table_name;
mysql> DESC mysql.user;
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------------+-----------------------------------+------+-----+-----------------------+-------+
| Host | char(60) | NO | PRI | | |
| User | char(32) | NO | PRI | | |
| Select_priv | enum('N','Y') | NO | | N | |
| Insert_priv | enum('N','Y') | NO | | N | |
| Update_priv | enum('N','Y') | NO | | N | |
| Delete_priv | enum('N','Y') | NO | | N | |
......
......
45 rows in set (0.00 sec)
//查看某表的创建命令
//语法:SHOW CREATE TABLE table_name;
mysql> SHOW CREATE TABLE mysql.user\G
*************************** 1. row ***************************
Table: user
Create Table: CREATE TABLE `user` (
`Host` char(60) COLLATE utf8_bin NOT NULL DEFAULT '',
`User` char(32) COLLATE utf8_bin NOT NULL DEFAULT '',
`Select_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
`Insert_priv` enum('N','Y') CHARACTER SET utf8 NOT NULL DEFAULT 'N',
......
......
PRIMARY KEY (`Host`,`User`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Users and global privileges'
1 row in set (0.00 sec)
//查看某表的状态
//语法:SHOW TABLE STATUS LIKE 'table_name'\G
mysql> USE mysql;
Database changed
mysql> SHOW TABLE STATUS LIKE 'user'\G
*************************** 1. row ***************************
Name: user
Engine: MyISAM
Version: 10
Row_format: Dynamic
Rows: 3
Avg_row_length: 128
Data_length: 508
Max_data_length: 281474976710655
Index_length: 4096
Data_free: 124
Auto_increment: NULL
Create_time: 2020-05-19 03:42:52
Update_time: 2020-05-20 20:58:09
Check_time: NULL
Collation: utf8_bin
Checksum: NULL
Create_options:
Comment: Users and global privileges
1 row in set (0.00 sec)
4.1.5 获取帮助
//获取命令使用帮助
//语法:HELP keyword
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) }
......
......
4.2 DML操作
DML操作包括增(insert)、删(delete、改(update)、查(select),均属针对表的操作
4.2.1 insert语句
//DML操作之增操作insert
//语法:insert [into] table_name [(column_name,...)] {VALUES | VALUE} (value1,...),(...),...
mysql> use school
Database changed
mysql> INSERT INTO school VALUE (1,'tom',20); //一次插入一条记录
Query OK, 1 row affected (0.00 sec)
//一次插入多条记录
mysql> insert school(id,name,age) value(2,'zhangsan',21),(3,'lisi',24),(4,'wangwu',25);
Query OK, 3 rows affected (0.01 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select* from school;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 1 | tom | 20 |
| 2 | zhangsan | 21 |
| 3 | lisi | 24 |
| 4 | wangwu | 25 |
+----+----------+------+
4 rows in set (0.00 sec)
4.2.2 select语句
字段column表示法
表示符 | 代表什么? |
---|---|
* | 所有字段 |
as | 字段别名,如col1 AS alias1 当表名很长时用别名代替 |
条件判断语句WHERE
操作类型 | 常用操作符 |
---|---|
操作符 | >,<,>=,<=,=,!= BETWEEN column# AND column# LIKE:模糊匹配 RLIKE:基于正则表达式进行模式匹配 IS NOT NULL:非空 IS NULL:空 |
条件逻辑操作 | AND OR NOT |
ORDER BY:排序,默认为升序(ASC)
ORDER BY语句 | 意义 |
---|---|
ORDER BY ‘column_name' | 根据column_name进行升序排序 |
ORDER BY 'column_name' DESC | 根据column_name进行降序排序 |
ORDER BY ’column_name' LIMIT 2 | 根据column_name进行升序排序 并只取前2个结果 |
ORDER BY ‘column_name' LIMIT 1,2 | 根据column_name进行升序排序 并且略过第1个结果取后面的2个结果 |
//DML操作之查操作select
//语法:SELECT column1,column2,... FROM table_name [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];
//查看表的全部信息
mysql> select * from student;
+----+-------------+------+
| id | name | age |
+----+-------------+------+
| 1 | tom | 20 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangsan | 26 |
| 6 | zhangsan | 20 |
| 7 | lisi | NULL |
| 8 | chenshuo | 10 |
| 9 | wangwu | 3 |
| 10 | qiuyi | 15 |
| 11 | qiuxiaotian | 20 |
+----+-------------+------+
11 rows in set (0.00 sec)
//字段别名
mysql> select id,name as 名字,age from student;
+----+-------------+------+
| id | 名字 | age |
+----+-------------+------+
| 1 | tom | 20 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangsan | 26 |
| 6 | zhangsan | 20 |
| 7 | lisi | NULL |
| 8 | chenshuo | 10 |
| 9 | wangwu | 3 |
| 10 | qiuyi | 15 |
| 11 | qiuxiaotian | 20 |
+----+-------------+------+
11 rows in set (0.00 sec)
//查找表中名字为zhangsan的记录
mysql> select * from student where name='zhangsan';
+----+----------+------+
| id | name | age |
+----+----------+------+
| 5 | zhangsan | 26 |
| 6 | zhangsan | 20 |
+----+----------+------+
2 rows in set (0.00 sec)
//查找表中名字为zhangsan且年龄大于20的记录
mysql> select * from student where name='zhangsan' and age > 20;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 5 | zhangsan | 26 |
+----+----------+------+
1 row in set (0.00 sec)
//查找student表中年龄在25到30的记录
mysql> select * from student where age between 25 and 30; //查找student表中年龄在25到30的记录
+----+----------+------+
| id | name | age |
+----+----------+------+
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangsan | 26 |
+----+----------+------+
3 rows in set (0.00 sec)
//查询student表中以年龄升序进行排序
mysql> select * from student order by age asc;
+----+-------------+------+
| id | name | age |
+----+-------------+------+
| 7 | lisi | NULL |
| 9 | wangwu | 3 |
| 8 | chenshuo | 10 |
| 10 | qiuyi | 15 |
| 1 | tom | 20 |
| 6 | zhangsan | 20 |
| 11 | qiuxiaotian | 20 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 5 | zhangsan | 26 |
| 4 | sean | 28 |
+----+-------------+------+
11 rows in set (0.00 sec)
//查询student表中以年龄升序进行排序(默认升序)
mysql> select * from student order by age;
+----+-------------+------+
| id | name | age |
+----+-------------+------+
| 7 | lisi | NULL |
| 9 | wangwu | 3 |
| 8 | chenshuo | 10 |
| 10 | qiuyi | 15 |
| 1 | tom | 20 |
| 6 | zhangsan | 20 |
| 11 | qiuxiaotian | 20 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 5 | zhangsan | 26 |
| 4 | sean | 28 |
+----+-------------+------+
11 rows in set (0.00 sec)
//查询student表中以年龄升序进行排序只取前2位
mysql> select * from student order by age limit 2;
+----+--------+------+
| id | name | age |
+----+--------+------+
| 7 | lisi | NULL |
| 9 | wangwu | 3 |
+----+--------+------+
2 rows in set (0.00 sec)
//查询student表中以年龄升序进行排序,忽略第一个,取后面两个
mysql> select * from student order by age limit 1,2;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 9 | wangwu | 3 |
| 8 | chenshuo | 10 |
+----+----------+------+
2 rows in set (0.00 sec)
//去掉年龄字段为空的记录后在排序
mysql> select * from student where age is not null order by age;
+----+-------------+------+
| id | name | age |
+----+-------------+------+
| 9 | wangwu | 3 |
| 8 | chenshuo | 10 |
| 10 | qiuyi | 15 |
| 1 | tom | 20 |
| 6 | zhangsan | 20 |
| 11 | qiuxiaotian | 20 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 5 | zhangsan | 26 |
| 4 | sean | 28 |
+----+-------------+------+
10 rows in set (0.00 sec)
//查询student表中年龄为空的记录
mysql> select * from student where age is null;
+----+------+------+
| id | name | age |
+----+------+------+
| 7 | lisi | NULL |
+----+------+------+
1 row in set (0.00 sec)
4.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 student;
+----+-------------+------+
| id | name | age |
+----+-------------+------+
| 1 | tom | 20 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangsan | 26 |
| 6 | zhangsan | 20 |
| 7 | lisi | NULL |
| 8 | chenshuo | 10 |
| 9 | wangwu | 3 |
| 10 | qiuyi | 15 |
| 11 | qiuxiaotian | 20 |
+----+-------------+------+
11 rows in set (0.00 sec)
//将tom的年龄改为30
mysql> update student set age=30 where name='tom';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from student;
+----+-------------+------+
| id | name | age |
+----+-------------+------+
| 1 | tom | 30 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangsan | 26 |
| 6 | zhangsan | 20 |
| 7 | lisi | NULL |
| 8 | chenshuo | 10 |
| 9 | wangwu | 3 |
| 10 | qiuyi | 15 |
| 11 | qiuxiaotian | 20 |
+----+-------------+------+
11 rows in set (0.00 sec)
4.2.4 dalect 语句
//语法:delete from table_name [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];
mysql> select * from student;
+----+-------------+------+
| id | name | age |
+----+-------------+------+
| 1 | tom | 30 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangsan | 26 |
| 6 | zhangsan | 20 |
| 7 | lisi | NULL |
| 8 | chenshuo | 10 |
| 9 | wangwu | 3 |
| 10 | qiuyi | 15 |
| 11 | qiuxiaotian | 20 |
+----+-------------+------+
11 rows in set (0.00 sec)
//删除id为6的记录
mysql> delete from student where id=6;
Query OK, 1 row affected (0.00 sec)
mysql> select * from student;
+----+-------------+------+
| id | name | age |
+----+-------------+------+
| 1 | tom | 30 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangsan | 26 |
| 7 | lisi | NULL |
| 8 | chenshuo | 10 |
| 9 | wangwu | 3 |
| 10 | qiuyi | 15 |
| 11 | qiuxiaotian | 20 |
+----+-------------+------+
10 rows in set (0.00 sec)
//删除id为9到11的记录
mysql> delete from student where id between 9 and 11;
Query OK, 3 rows affected (0.00 sec)
mysql> select * from student;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 1 | tom | 30 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangsan | 26 |
| 7 | lisi | NULL |
| 8 | chenshuo | 10 |
+----+----------+------+
7 rows in set (0.00 sec)
4.2.5 truncate 语句
truncate与delete的区别:
语句类型 | 特点 |
---|---|
delete | DELETE删除表内容时仅删除内容,但会保留表结构 DELETE语句每次删除一行,并在事务日志中为所删除的每行记录一项 可以通过回滚事务日志恢复数据 非常占用空间 |
truncate | 删除表中所有行,且无法恢复 表结构、约束和索引等保持不变,新添加的行计数值重置为初始值 执行速度比DELETE快,且使用的系统和事务日志资源少 通过释放存储表数据所用的数据页来删除数据,并且只在事务日志中记录页的释放 对于有外键约束引用的表,不能使用TRUNCATE TABLE删除数据 不能用于加入了索引视图的表 |
mysql> select * from student;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 1 | tom | 30 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangsan | 26 |
| 7 | lisi | NULL |
| 8 | chenshuo | 10 |
+----+----------+------+
7 rows in set (0.00 sec)
mysql> select * from student;
+----+----------+------+
| id | name | age |
+----+----------+------+
| 1 | tom | 30 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangsan | 26 |
| 7 | lisi | NULL |
| 8 | chenshuo | 10 |
+----+----------+------+
7 rows in set (0.00 sec)
mysql> truncate student;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from student;
Empty set (0.01 sec)
//表结构没有被删除
mysql> desc student;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(100) | NO | | NULL | |
| age | tinyint(4) | YES | | NULL | |
+-------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
4.3 DCL操作
4.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];
//创建一个tom用户,允许他在school库的student表中插入数据
mysql> grant insert on school.student to 'tom'@'localhost' identified by '123456';
Query OK, 0 rows affected, 1 warning (0.01 sec)
//另一台终端上登录
[root@localhost ~]# mysql -utom -p123456
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| school |
+--------------------+
2 rows in set (0.01 sec)
mysql> use school;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
//只能看到student表
mysql> show tables;
+------------------+
| Tables_in_school |
+------------------+
| student |
+------------------+
1 row in set (0.00 sec)
//没有select权限,无法查看
mysql> select * from student;
ERROR 1142 (42000): SELECT command denied to user 'tom'@'localhost' for table 'student'
//插入一行数据
mysql> insert student(name,age) value('tom',20);
Query OK, 1 row affected (0.00 sec)
//由于没有权限查看,回原终端查看
mysql> select * from student;
+----+------+------+
| id | name | age |
+----+------+------+
| 1 | tom | 20 |
+----+------+------+
1 row in set (0.00 sec)
//创建jerry用户,给它有对school库的student表的select权限
mysql> create user 'jerry'@'localhost' identified by '123456';
Query OK, 0 rows affected (0.00 sec)
mysql> grant select on school.student to 'jerry'@'localhost';
Query OK, 0 rows affected (0.00 sec)
//刷新权限
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
//Jerry用户登录
[root@localhost ~]# mysql -ujerry -p123456
mysql> use school
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> show tables;
+------------------+
| Tables_in_school |
+------------------+
| student |
+------------------+
1 row in set (0.00 sec)
//只有select的权限
mysql> select * from student;
+----+------+------+
| id | name | age |
+----+------+------+
| 1 | tom | 20 |
+----+------+------+
1 row in set (0.00 sec)
mysql> update student set age=20 where id=1;
ERROR 1142 (42000): UPDATE command denied to user 'jerry'@'localhost' for table 'student'
mysql> insert student(name,age) value('zhangsan',20);
ERROR 1142 (42000): INSERT command denied to user 'jerry'@'localhost' for table 'student'
实例
//授权zhangsan用户在数据库本机上登录访问所有数据库
mysql> grant all on *.* to 'zhangsan'@'localhost' identified by '123456';
Query OK, 0 rows affected, 1 warning (0.00 sec)
//授权lisi用户在192.168.8.0网段上登录,并对mysql库的user表有所有权限
mysql> grant all on mysql.user to 'lisi'@'192.168.8.%' identified by '123456';
Query OK, 0 rows affected, 1 warning (0.00 sec)
4.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)
//查看指定用户tom的授权信息
mysql> show grants for 'tom'@'localhost';
+---------------------------------------------------------+
| Grants for tom@localhost |
+---------------------------------------------------------+
| GRANT USAGE ON *.* TO 'tom'@'localhost' |
| GRANT INSERT ON `school`.`student` TO 'tom'@'localhost' |
+---------------------------------------------------------+
2 rows in set (0.00 sec)
4.3.3 取消授权revoke
//语法:revoke priv_type,... ON db_name.table_name FROM 'username'@'host';
//zhangsan用户在本地有所有权限
mysql> show grants for 'zhangsan'@'localhost';
+-------------------------------------------------------+
| Grants for zhangsan@localhost |
+-------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'zhangsan'@'localhost' |
+-------------------------------------------------------+
1 row in set (0.00 sec)
//删除本地用户张三所有库所有表的select权限
mysql> revoke select on *.* from 'zhangsan'@'localhost';
Query OK, 0 rows affected (0.00 sec)
//查看剩余权限
mysql> show grants for 'zhangsan'@'localhost';
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Grants for zhangsan@localhost |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| GRANT INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER, CREATE TABLESPACE ON *.* TO 'zhangsan'@'localhost' |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql服务进程启动时会读取mysql库中的所有授权表至内存中:
- GRANT或REVOKE等执行权限操作会保存于表中,mysql的服务进程会自动重读授权表,并更新至内存中
- 对于不能够或不能及时重读授权表的命令,可手动让mysql的服务进程重读授权表
mysql> FLUSH PRIVILEGES;
4.4 group by
GROUP BY 语句用于结合合计函数,根据一个或多个列对结果集进行分组。
GROUP BY必须得配合聚合函数来用,分组之后你可以计数(COUNT),求和(SUM),求平均数(AVG)等。
常用聚合函数
- count() 计数
- sum() 求和
- avg() 平均数
- max() 最大值
- min() 最小值
4.4.1 group by 子句
作用:根据数据列的每个成员对查询结果进行分组(分类)统计,最终得到一个分组汇总表。
语法:select 列名 , 列函数 from 表名 group by 列名;
实例:
1.创建staff表,表中包含id、name、dept、salary、edlevel、hiredate,如下图
mysql> create table staff( id int unsigned primary key, name varchar(10) not nulll,e );
Query OK, 0 rows affected (0.00 sec)
mysql> desc staff;
+----------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+------------------+------+-----+---------+-------+
| id | int(10) unsigned | NO | PRI | NULL | |
| name | varchar(10) | NO | | NULL | |
| dept | varchar(20) | NO | | NULL | |
| salary | int(11) | NO | | NULL | |
| edlevel | tinyint(4) | YES | | NULL | |
| hiredate | date | YES | | NULL | |
+----------+------------------+------+-----+---------+-------+
6 rows in set (0.00 sec)
2.插入员工信息
//因为编码为latin1,不支持中文,所以修改中文编码
//查看编码
mysql> show create table staff\G
*************************** 1. row ***************************
Table: staff
Create Table: CREATE TABLE `staff` (
`id` int(10) unsigned NOT NULL,
`name` varchar(10) NOT NULL,
`dept` varchar(20) NOT NULL,
`salary` int(11) NOT NULL,
`edlevel` tinyint(4) DEFAULT NULL,
`hiredate` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
//修改表的编码
mysql> alter table staff character set 'utf8mb4';
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
//name和dept字段编码任然是latin1
mysql> show create table staff\G
*************************** 1. row ***************************
Table: staff
Create Table: CREATE TABLE `staff` (
`id` int(10) unsigned NOT NULL,
`name` varchar(10) CHARACTER SET latin1 NOT NULL,
`dept` varchar(20) CHARACTER SET latin1 NOT NULL,
`salary` int(11) NOT NULL,
`edlevel` tinyint(4) DEFAULT NULL,
`hiredate` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
1 row in set (0.00 sec)
//直接改成文本,设置中文编码
mysql> alter table `staff` change `name` `name` text character set 'utf8mb4';
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> alter table `staff` change `dept` `detp` text character set 'utf8mb4';
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql>
mysql> show create table staff\G
*************************** 1. row ***************************
Table: staff
Create Table: CREATE TABLE `staff` (
`id` int(10) unsigned NOT NULL,
`name` text,
`detp` text,
`salary` int(11) NOT NULL,
`edlevel` tinyint(4) DEFAULT NULL,
`hiredate` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
1 row in set (0.00 sec)
插入数据
mysql> insert into staff value(1,'张三','开发部',5880,6,'2018-9-10'),(2,'林辰','设计部',8880,8,'2018-1-10'),(3,'毕晨','开发部',10880,9,'2019-2-1'),(4,'李晨','开发部',12680,10,'2016-2-1'),(5,'林尚','开发部',22680,11,'2017-2-1'),(6,'李华','美化部',52800,12,'2018-5-6'),(7,'林晓','美化部',68880,15,'2019-6-1'),(8,'毕芬',' 运维部',6880,10,'2018-2-8');
Query OK, 8 rows affected (0.00 sec)
Records: 8 Duplicates: 0 Warnings: 0
//查看staff表的数据
mysql> select * from staff;
+----+--------+-----------+--------+---------+------------+
| id | name | detp | salary | edlevel | hiredate |
+----+--------+-----------+--------+---------+------------+
| 1 | 张三 | 开发部 | 5880 | 6 | 2018-09-10 |
| 2 | 林辰 | 设计部 | 8880 | 8 | 2018-01-10 |
| 3 | 毕晨 | 开发部 | 10880 | 9 | 2019-02-01 |
| 4 | 李晨 | 开发部 | 12680 | 10 | 2016-02-01 |
| 5 | 林尚 | 开发部 | 22680 | 11 | 2017-02-01 |
| 6 | 李华 | 美化部 | 52800 | 12 | 2018-05-06 |
| 7 | 林晓 | 美化部 | 68880 | 15 | 2019-06-01 |
| 8 | 毕芬 | 运维部 | 6880 | 10 | 2018-02-08 |
+----+--------+-----------+--------+---------+------------+
8 rows in set (0.00 sec)
3.查询每个部门的最高薪水
mysql> select detp,max(salary) as 最高薪水 from staff group by detp;
+-----------+--------------+
| detp | 最高薪水 |
+-----------+--------------+
| 开发部 | 22680 |
| 美化部 | 68880 |
| 设计部 | 8880 |
| 运维部 | 6880 |
+-----------+--------------+
4 rows in set (0.00 sec)
4.查询每个部门的总薪水
mysql> select detp,sum(salary) as 总薪水 from staff group by detp;
+-----------+-----------+
| detp | 总薪水 |
+-----------+-----------+
| 开发部 | 52120 |
| 美化部 | 121760 |
| 设计部 | 8880 |
| 运维部 | 6880 |
+-----------+-----------+
4 rows in set (0.00 sec)
4.4.2 where子句与group by 子句同时使用
作用:在查询之前将不满足where子句的行去掉,再进行分组查询。where子句必须在group by子句的前面。
语法:select 列名 , 列函数 from 表名 where 条件 group by 列名;
案例:
1.查询公司各部门的最高薪水
mysql> select detp,max(salary) as 最高薪水 from staff group by detp;
+-----------+--------------+
| detp | 最高薪水 |
+-----------+--------------+
| 开发部 | 22680 |
| 美化部 | 68880 |
| 设计部 | 8880 |
| 运维部 | 6880 |
+-----------+--------------+
4 rows in set (0.00 sec)
2.查询2018年后各公司各部门的最高薪资
mysql> select detp,max(salary) as 最高薪水 from staff where hiredate > '2018-01-01' group by detp;
+-----------+--------------+
| detp | 最高薪水 |
+-----------+--------------+
| 开发部 | 10880 |
| 美化部 | 68880 |
| 设计部 | 8880 |
| 运维部 | 6880 |
+-----------+--------------+
4 rows in set (0.00 sec)
3.在group by之后使用having
作用:having 子句的作用是筛选满足条件的组,即在分组之后过滤数据,条件中经常包含聚组函数,使用having 条件显示特定的组,也可以使用多个分组标准进行分组。
语法:select 列名 , 列函数 from 表名 where 条件 group by 列名 having 子句;
案例:
1.求公司各部门最高薪资
mysql> select detp,max(salary) as 最高薪水 from staff group by detp;
+-----------+--------------+
| detp | 最高薪水 |
+-----------+--------------+
| 开发部 | 22680 |
| 美化部 | 68880 |
| 设计部 | 8880 |
| 运维部 | 6880 |
+-----------+--------------+
4 rows in set (0.00 sec)
2.求公司各部门最高薪资大于10000的人
mysql> select name,detp,max(salary) as 最高薪水 from staff group by detp,name having 最高薪水 > 10000;
+--------+-----------+--------------+
| name | detp | 最高薪水 |
+--------+-----------+--------------+
| 李晨 | 开发部 | 12680 |
| 林尚 | 开发部 | 22680 |
| 毕晨 | 开发部 | 10880 |
| 李华 | 美化部 | 52880 |
| 林晓 | 美化部 | 68880 |
+--------+-----------+--------------+
5 rows in set (0.00 sec)