一. 关系型数据库介绍
1.1 数据结构模型
数据结构模型主要有:
- 层次模型
- 网状结构
- 关系模型
关系模型:
二维关系:row,column
数据库管理系统:DBMS
关系:Relational,RDBMS
1.2 RDBMS专业名词
- MySQL:MySQL,MariaDB,Percona-Server
- PostgreSQL:简称为pgsql
- Oracle
- MSSQL
事务:多个操作被当作一个整体对待就称为一个事务
要看一个关系型数据库是否支持事务,需要看其是否支持并满足ACID测试
ACID:ACID是事务的一个基本标准
- A:Automicity,原子性
- C:Consistency,一致性
- I:Isolation,隔离性
- D:Durability,持久性
如果你对ACID感兴趣,可以查看这里了解详细说明,ACID将不作为我们讲解的重点。
SQL:Structure Query Language,结构化查询语言
约束:constraint,向数据表提供的数据要遵守的限制
- 主键约束:一个或多个字段的组合,填入的数据必须能在本表中唯一标识本行。且必须提供数据,不能为空(NOT NULL)。
- 一个表只能存在一个
- 惟一键约束:一个或多个字段的组合,填入的数据必须能在本表中唯一标识本行。允许为空(NULL)
- 一个表可以存在多个
- 外键约束:一个表中的某字段可填入数据取决于另一个表的主键已有的数据
- 检查性约束
索引:将表中的一个或多个字段中的数据复制一份另存,并且这些数据需要按特定次序排序存储
关系运算:
- 选择:挑选出符合条件的行(部分行)
- 投影:挑选出需要的字段
- 连接
数据抽象方式:
- 物理层:决定数据的存储格式,即RDBMS在磁盘上如何组织文件
- 逻辑层:描述DB存储什么数据,以及数据间存在什么样的关系
- 视图层:描述DB中的部分数据
1.3 关系型数据库的常见组件
关系型数据库的常见组件有:
- 数据库:database
- 表:table,由行(row)和列(column)组成
- 索引:index
- 视图:view
- 用户:user
- 权限:privilege
- 存储过程:procedure
- 存储函数:function
- 触发器:trigger
- 事件调度器:event scheduler
1.4 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:移除授权 |
二. mysql的程序组成
- 客户端
- mysql:CLI交互式客户端程序
- mysql_secure_installation:安全初始化,强烈建议安装完以后执行此命令
- mysqldump:mysql备份工具
- mysqladmin
- 服务器端
- mysqld
2.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.23, for Linux (x86_64) using EditLine wrapper
[root@localhost ~]# mysql -uroot -pwangqing123! -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 4
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>
//注意,不推荐直接在命令行里直接用-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 5
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>
[root@localhost ~]# mysql -uroot -p -h 127.0.0.1 -e 'SHOW DATABASES;'
Enter password:
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
| wangqingge |
+--------------------+
2.2 服务器监听的两种socket地址
socket类型 | 说明 |
---|---|
ip socket | 默认监听在tcp的3306端口,支持远程通信 |
unix sock | 监听在sock文件上(/tmp/mysql.sock,/var/lib/mysql/mysql.sock)仅支持本地通信server地址只能是:localhost,127.0.0.1 |
三. mysql安装与配置
3.1 mysql安装
mysql安装方式有三种:
- 源代码:编译安装
- 二进制格式的程序包:展开至特定路径,并经过简单配置后即可使用
- 程序包管理器管理的程序包:
- rpm:有两种
- OS Vendor:操作系统发行商提供的
- 项目官方提供的
- deb
- rpm:有两种
3.2 mysql配置
编译安装mysql
# 安装依赖包和开发工具包
yum -y install libevent* libtool* autoconf* libstd* ncurse* bison* openssl* gcc gcc-c++ bzip2*
yum -y groupinstall "Development Tools"
# 下载cmake编译工具
[root@96 ~]# cd /usr/src/
[root@96 src]# wget http://www.cmake.org/files/v2.8/cmake-2.8.12.1.tar.gz
下载过程略。。。
[root@96 src]# ls
cmake-2.8.12.1.tar.gz
# 解压
[root@96 src]# tar xf cmake-2.8.12.1.tar.gz
[root@96 src]# ls
cmake-2.8.12.1 cmake-2.8.12.1.tar.gz
# 编译安装cmake
[root@96 ~]# cd /usr/src/cmake-2.8.12.1
[root@96 cmake-2.8.12.1]# ./configure && make && make install
# 编译安装mysql5.7.26
[root@96 cmake-2.8.12.1]# cd /usr/src/
[root@96 src]# wget http://downloads.mysql.com/archives/get/file/mysql-5.7.26.tar.gz
[root@96 src]# ls
cmake-2.8.12.1 cmake-2.8.12.1.tar.gz kernels mysql-5.7.26.tar.gz
[root@96 src]# tar xf mysql-5.7.26.tar.gz
[root@96 src]# cd mysql-5.7.26
[root@96 mysql-5.7.26]# cmake \
-DCMAKE_INSTALL_PREFIX=/usr/local/mysql \
-DMYSQL_DATADIR=/usr/local/mysql/data \
-DSYSCONFDIR=/etc \
-DWITH_MYISAM_STORAGE_ENGINE=1 \
-DWITH_INNOBASE_STORAGE_ENGINE=1 \
-DWITH_MEMORY_STORAGE_ENGINE=1 \
-DWITH_READLINE=1 \
-DMYSQL_UNIX_ADDR=/var/lib/mysql/mysql.sock \
-DMYSQL_TCP_PORT=3306 \
-DENABLED_LOCAL_INFILE=1 \
-DWITH_PARTITION_STORAGE_ENGINE=1 \
-DEXTRA_CHARSETS=all \
-DDEFAULT_CHARSET=utf8 \
-DDEFAULT_COLLATION=utf8_general_ci \
-DDOWNLOAD_BOOST=1 -DWITH_BOOST=/usr/src/mysql-5.7.26/include/boost_1_59_0/patches/boost
编译过程略.....
[root@96 mysql-5.7.26]# make && make install
# 创建mysql用户和组
[root@96 mysql-5.7.26]# groupadd mysql
[root@96 mysql-5.7.26]# useradd -M -s /sbin/nologin -g mysql mysql
# 设置环境变量
[root@96 mysql-5.7.26]# cd /usr/local/mysql/
[root@96 mysql]# echo 'export PATH=/usr/local/mysql/bin:$PATH' >/etc/profile.d/mysql.sh
[root@96 mysql]# . /etc/profile.d/mysql.sh
# 初始化数据库
[root@96 mysql]# mysql_install_db --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data --user=mysql
2019-08-17 17:29:43 [WARNING] mysql_install_db is deprecated. Please consider switching to mysqld --initialize
2019-08-17 17:29:45 [WARNING] The bootstrap log isn't empty:
2019-08-17 17:29:45 [WARNING] 2019-08-17T09:29:43.936116Z 0 [Warning] --bootstrap is deprecated. Please consider using --initialize instead
2019-08-17T09:29:43.936687Z 0 [Warning] Changed limits: max_open_files: 1024 (requested 5000)
2019-08-17T09:29:43.936692Z 0 [Warning] Changed limits: table_open_cache: 431 (requested 2000)
# 修改配置文件
[root@96 mysql]# sed -i '11,13d' /etc/my.cnf
[root@96 mysql]# sed -ri 's#^(datadir=).*#\1/usr/local/mysql/data#g' /etc/my.cnf
[root@96 mysql]# sed -ri 's#^(socket=).*#\1/tmp/mysql.sock#g' /etc/my.cnf
# 设置服务启动脚本
[root@96 mysql]# cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
[root@96 mysql]# sed -ri 's#^(basedir=).*#\1/usr/local/mysql#g' /etc/init.d/mysqld
[root@96 mysql]# sed -ri 's#^(datadir=).*#\1/usr/local/mysql/data#g' /etc/init.d/mysqld
# 启动服务
[root@96 mysql]# service mysqld start
Starting MySQL.Logging to '/usr/local/mysql/data/96.err'.
SUCCESS!
[root@96 mysql]# chkconfig mysqld on
[root@96 mysql]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:111 *:*
LISTEN 0 128 *:22 *:*
LISTEN 0 80 :::3306 :::*
LISTEN 0 128 :::111 :::*
LISTEN 0 128 :::22 :::*
- mysql破解密码
# 编辑配置文件
[root@96 ~]# echo "skip-grant-tables" >> /etc/my.cnf
[root@96 ~]# service mysqld restart
Shutting down MySQL. SUCCESS!
Starting MySQL. SUCCESS!
[root@96 ~]# mkdir /var/lib/mysql
[root@96 ~]# ln -s /tmp/mysql.sock /var/lib/mysql/mysql.sock
# 不使用密码登录进去
[root@96 ~]# mysql -uroot
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.26 Source distribution
Copyright (c) 2000, 2019, 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> use mysql; #进去mysql数据库
mysql> update user set authentication_string = password('shicailun666!') where User = 'root'; #重置mysql密码
mysql> quit #退出
Bye
[root@96 ~]# sed -i /skip-grant-tables/d /etc/my.cnf # 将配置文件中跳过授权表删除
# 重启服务
[root@96 ~]# service mysqld restart
Shutting down MySQL. SUCCESS!
Starting MySQL. SUCCESS!
# 使用新密码登录
[root@96 ~]# mysql -uroot -p'shicailun666!'
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.26
Copyright (c) 2000, 2019, 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>
yum安装mysql
//配置mysql的yum源
[root@localhost ~]# cd /usr/src/
[root@localhost src]# ls
debug kernels
[root@localhost src]# wget http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm
下载过程略
[root@localhost src]# ls
debug kernels mysql57-community-release-el7-10.noarch.rpm
[root@localhost src]# yum -y install mysql57-community-release-el7-10.noarch.rpm
Loaded plugins: fastestmirror, product-id, search-disabled-repos, subscription-
: manager
This system is not registered with an entitlement server. You can use subscription-manager to register.
Examining mysql57-community-release-el7-10.noarch.rpm: mysql57-community-release-el7-10.noarch
....
Installed:
mysql57-community-release.noarch 0:el7-10
Complete!
[root@localhost ~]# ls /etc/yum.repos.d/
mysql-community.repo mysql-community-source.repo
//安装mysql5.7
[root@localhost ~]# yum -y install mysql-community-server mysql-community-client mysql-community-common mysql-community-devel
Loaded plugins: fastestmirror, product-id, search-disabled-repos, subscription-
: manager
This system is not registered with an entitlement server. You can use subscription-manager to register.
Loading mirror speeds from cached hostfile
Resolving Dependencies
--> Running transaction check
---> Package mysql-community-client.x86_64 0:5.7.23-1.el7 will be installed
--> Processing Dependency: mysql-community-libs(x86-64) >= 5.7.9 for package: mysql-community-client-5.7.23-1.el7.x86_64
....
Installed:
mysql-community-client.x86_64 0:5.7.23-1.el7
mysql-community-common.x86_64 0:5.7.23-1.el7
mysql-community-devel.x86_64 0:5.7.23-1.el7
mysql-community-libs.x86_64 0:5.7.23-1.el7
mysql-community-libs-compat.x86_64 0:5.7.23-1.el7
mysql-community-server.x86_64 0:5.7.23-1.el7
Replaced:
mariadb-libs.x86_64 1:5.5.56-2.el7
Complete!
//启动mysql
[root@localhost ~]# systemctl start mysqld
[root@localhost ~]# systemctl status mysqld
● mysqld.service - MySQL Server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
Active: active (running) since Sun 2018-08-12 23:39:33 CST; 6s ago
Docs: man:mysqld(8)
http://dev.mysql.com/doc/refman/en/using-systemd.html
Process: 1325 ExecStart=/usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid $MYSQLD_OPTS (code=exited, status=0/SUCCESS)
Process: 1249 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
Main PID: 1327 (mysqld)
CGroup: /system.slice/mysqld.service
└─1327 /usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/my...
Aug 12 23:39:26 localhost.localdomain systemd[1]: Starting MySQL Server...
Aug 12 23:39:33 localhost.localdomain systemd[1]: Started MySQL Server.
//确保3306端口已经监听起来
[root@localhost ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 :::22 :::*
LISTEN 0 100 ::1:25 :::*
LISTEN 0 80 :::3306 :::*
//在日志文件中找出临时密码
[root@localhost ~]# grep "password" /var/log/mysqld.log
2018-08-12T15:39:28.710830Z 1 [Note] A temporary password is generated for root@localhost: &vsD!YuKT7&/
//此处的临时密码为&vsD!YuKT7&/
//注意,你的密码跟这是不一样的,一定要看清楚,禁止直接复制我这里的密码
//使用获取到的临时密码登录mysql
[root@localhost ~]# mysql -uroot -p
Enter password: //此处输入密码,可以直接复制你的密码粘贴至此处,也可手动输入
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.23
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> //看到有这样的标识符则表示成功登录了
//修改mysql登录密码
mysql> set global validate_password_policy=0;
Query OK, 0 rows affected (0.00 sec)
mysql> set global validate_password_length=1;
Query OK, 0 rows affected (0.01 sec)
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'wangqing123!';
Query OK, 0 rows affected (0.00 sec)
mysql> quit
Bye
//为避免mysql自动升级,这里需要卸载最开始安装的yum源
[root@localhost ~]# rpm -qa|grep mysql
mysql-community-server-5.7.23-1.el7.x86_64
mysql57-community-release-el7-10.noarch
mysql-community-common-5.7.23-1.el7.x86_64
mysql-community-client-5.7.23-1.el7.x86_64
mysql-community-libs-compat-5.7.23-1.el7.x86_64
mysql-community-libs-5.7.23-1.el7.x86_64
mysql-community-devel-5.7.23-1.el7.x86_64
[root@localhost ~]# yum -y remove mysql57-community-release-el7-10.noarch
Loaded plugins: fastestmirror, product-id, search-disabled-repos, subscription-
: manager
This system is not registered with an entitlement server. You can use subscription-manager to register.
Resolving Dependencies
--> Running transaction check
....
Removed:
mysql57-community-release.noarch 0:el7-10
Complete!
四. mysql数据库操作
4.1 DDL操作
4.1.1 数据库操作
//创建数据库
//语法:CREATE DATABASE [IF NOT EXISTS] 'DB_NAME';
//创建数据库wangqingge
mysql> CREATE DATABASE IF NOT EXISTS wangqingge;
Query OK, 1 row affected (0.00 sec)
//查看当前实例有哪些数据库
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
| wangqingge |
+--------------------+
5 rows in set (0.00 sec)
//删除数据库
//语法:DROP DATABASE [IF EXISTS] 'DB_NAME';
//删除数据库wangqingge
mysql> DROP DATABASE IF EXISTS wangqingge;
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)
4.1.2 表操作
//创建表
//语法:CREATE TABLE table_name (col1 datatype 修饰符,col2 datatype 修饰符) ENGINE='存储引擎类型';
//在数据库wangqingge里创建表wangqing
mysql> CREATE DATABASE wangqingge; //创建数据库wangqingge
Query OK, 1 row affected (0.00 sec)
mysql> use wangqingge; //进入wangqingge数据库
Database changed
mysql> CREATE TABLE wangqing (id int NOT NULL,name VARCHAR(100) NOT NULL,age tinyint); //创建wangqing表
Query OK, 0 rows affected (0.09 sec)
//查看当前数据库有哪些表
mysql> SHOW TABLES;
+----------------------+
| Tables_in_wangqingge |
+----------------------+
| wangqing |
+----------------------+
1 row in set (0.00 sec)
//删除表
//语法:DROP TABLE [ IF EXISTS ] 'table_name';
//删除表wangqing
mysql> DROP TABLE wangqing;
Query OK, 0 rows affected (0.01 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'];
//创建数据库用户wangqing
mysql> CREATE USER 'wangqing'@'127.0.0.1' IDENTIFIED BY 'wangqing123!';
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges; //刷新权限
//使用新创建的用户和密码登录
[root@localhost ~]# mysql -uwangqing -pwangqing123! -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';
mysql> DROP USER 'wangqing'@'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 |
| koi8r | KOI8-R Relcom Russian | koi8r_general_ci | 1 |
| latin1 | cp1252 West European | latin1_swedish_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 |
| sys |
| wangqingge |
+--------------------+
5 rows in set (0.00 sec)
mysql> SHOW TABLES FROM wangqingge; //不进入某数据库而列出其包含的所有表
+----------------------+
| Tables_in_wangqingge |
+----------------------+
| wangqing |
+----------------------+
1 row in set (0.00 sec)
//查看表结构
//语法:DESC [db_name.]table_name;
mysql> DESC wangqingge.wangqing;
+-------+--------------+------+-----+---------+-------+
| 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 wangqingge.wangqing;
+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| wangqing | CREATE TABLE `wangqing` (
`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 wangqingge; //进入数据库wangqingge
Database changed
mysql> SHOW TABLE STATUS LIKE 'wangqing'\G //查看wangqing表的状态
*************************** 1. row ***************************
Name: wangqing
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)
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
......
......
4.2 DML操作
DML操作包括增(INSERT)、删(DELETE)、改(UPDATE)、查(SELECT),均属针对表的操作。
4.2.1 INSERT语句-添加
//语法:INSERT [INTO] table_name [(column_name,...)] {VALUES | VALUE} (value1,...),(...),...
mysql> use wangqingge;
Database changed
mysql> INSERT INTO wangqing (id,name,age) VALUE (1,'tom',20); //一次插入一条记录
Query OK, 1 row affected (0.01 sec)
mysql> INSERT INTO wangqing (id,name,age) VALUES (2,'jerry',23),(3,'wangqing',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
4.2.2 SELECT语句-查看
字段column表示法
表示符 | 代表什么? |
---|---|
* | 所有字段 |
as | 字段别名,如col1 AS alias1当表名很长时用别名代替 |
条件判断语句WHERE
操作类型 | 常用操作符 |
---|---|
操作符 | >,<,>=,<=,=,!=BETWEEN column# AND column#LIKE:模糊匹配RLIKE:基于正则表达式进行模式匹配IS NOT NULL:非空IS NULL:空 |
条件逻辑操作 | ANDORNOT |
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个结果 |
//语法:SELECT column1,column2,... FROM table_name [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];
mysql> use wangqingge;
Database changed
mysql> select * from wangqing;
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 1 | tom | 20 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangshan | 26 |
| 6 | zhangshan | 20 |
| 7 | lisi | NULL |
+----+-----------+------+
7 rows in set (0.00 sec)
mysql> SELECT name FROM wangqing;
+-----------+
| name |
+-----------+
| tom |
| jerry |
| wangqing |
| sean |
| zhangshan |
| zhangshan |
| lisi |
+-----------+
7 rows in set (0.01 sec)
mysql> SELECT * FROM wangqing ORDER BY age;
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 7 | lisi | NULL |
| 1 | tom | 20 |
| 6 | zhangshan | 20 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 5 | zhangshan | 26 |
| 4 | sean | 28 |
+----+-----------+------+
7 rows in set (0.00 sec)
mysql> SELECT * FROM wangqing ORDER BY age DESC;
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 4 | sean | 28 |
| 5 | zhangshan | 26 |
| 3 | wangqing | 25 |
| 2 | jerry | 23 |
| 1 | tom | 20 |
| 6 | zhangshan | 20 |
| 7 | lisi | NULL |
+----+-----------+------+
7 rows in set (0.00 sec)
mysql> SELECT * FROM wangqing ORDER BY age limit 2;
+----+------+------+
| id | name | age |
+----+------+------+
| 7 | lisi | NULL |
| 1 | tom | 20 |
+----+------+------+
2 rows in set (0.00 sec)
mysql> SELECT * FROM wangqing ORDER BY age limit 1,2;
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 1 | tom | 20 |
| 6 | zhangshan | 20 |
+----+-----------+------+
2 rows in set (0.00 sec)
mysql> SELECT * FROM wangqing WHERE age >= 25;
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangshan | 26 |
+----+-----------+------+
3 rows in set (0.00 sec)
mysql> SELECT * FROM wangqing WHERE age >= 25 AND name = 'zhangshan';
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 5 | zhangshan | 26 |
+----+-----------+------+
1 row in set (0.00 sec)
mysql> SELECT * FROM wangqing WHERE age BETWEEN 23 and 28;
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangshan | 26 |
+----+-----------+------+
4 rows in set (0.00 sec)
mysql> select * from wangqing where age is not null;
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 1 | tom | 20 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangshan | 26 |
| 6 | zhangshan | 20 |
+----+-----------+------+
6 rows in set (0.00 sec)
mysql> select * from wangqing where age is null;
+----+------+------+
| id | name | age |
+----+------+------+
| 7 | lisi | NULL |
+----+------+------+
1 row in set (0.00 sec)
4.2.3 update语句-修改
//语法:UPDATE table_name SET column1 = new_value1[,column2 = new_value2,...] [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];
mysql> select * from wangqing;
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 1 | tom | 20 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangshan | 26 |
| 6 | zhangshan | 20 |
| 7 | lisi | NULL |
+----+-----------+------+
7 rows in set (0.00 sec)
mysql> update wangqing set age = 30 where name = 'lisi';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from wangqing where name = 'lisi';
+----+------+------+
| id | name | age |
+----+------+------+
| 7 | lisi | 30 |
+----+------+------+
1 row in set (0.00 sec)
4.2.4 delete语句-删除
//语法:DELETE FROM table_name [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];
mysql> select * from wangqing;
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 1 | tom | 20 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangshan | 26 |
| 6 | zhangshan | 20 |
| 7 | lisi | 30 |
+----+-----------+------+
7 rows in set (0.00 sec)
mysql> delete from wangqing where id = 7; //删除某条记录
Query OK, 1 row affected (0.00 sec)
mysql> select * from wangqing;
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 1 | tom | 20 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangshan | 26 |
| 6 | zhangshan | 20 |
+----+-----------+------+
6 rows in set (0.00 sec)
mysql> delete from wangqing; //删除整张表的内容
Query OK, 6 rows affected (0.00 sec)
mysql> select * from wangqing;
Empty set (0.00 sec)
mysql> desc wangqing;
+-------+--------------+------+-----+---------+-------+
| 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)
4.2.5 truncate语句
truncate与delete的区别:
语句类型 | 特点 |
---|---|
delete | DELETE删除表内容时仅删除内容,但会保留表结构DELETE语句每次删除一行,并在事务日志中为所删除的每行记录一项可以通过回滚事务日志恢复数据非常占用空间 |
truncate | 删除表中所有数据,且无法恢复表结构、约束和索引等保持不变,新添加的行计数值重置为初始值执行速度比DELETE快,且使用的系统和事务日志资源少通过释放存储表数据所用的数据页来删除数据,并且只在事务日志中记录页的释放对于有外键约束引用的表,不能使用TRUNCATE TABLE删除数据不能用于加入了索引视图的表 |
//语法:TRUNCATE table_name;
mysql> select * from wangqing;
+----+-----------+------+
| id | name | age |
+----+-----------+------+
| 1 | tom | 20 |
| 2 | jerry | 23 |
| 3 | wangqing | 25 |
| 4 | sean | 28 |
| 5 | zhangshan | 26 |
| 6 | zhangshan | 20 |
| 7 | lisi | NULL |
+----+-----------+------+
7 rows in set (0.00 sec)
mysql> truncate wangqing;
Query OK, 0 rows affected (0.01 sec)
mysql> select * from wangqing;
Empty set (0.00 sec)
mysql> desc wangqing;
+-------+--------------+------+-----+---------+-------+
| 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)
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];
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
| wangqingge |
+--------------------+
5 rows in set (0.00 sec)
//授权wangqing用户在数据库本机上登录访问所有数据库
mysql> GRANT ALL ON *.* TO 'wangqing'@'localhost' IDENTIFIED BY 'wangqing123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> GRANT ALL ON *.* TO 'wangqing'@'127.0.0.1' IDENTIFIED BY 'wangqing123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)
//授权wangqing用户在172.16.12.129上远程登录访问wangqingge数据库
mysql> GRANT ALL ON wangqingge.* TO 'wangqing'@'172.16.12.129' IDENTIFIED BY 'wangqing123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)
//授权wangqing用户在所有位置上远程登录访问wangqingge数据库
mysql> GRANT ALL ON *.* TO 'wangqing'@'%' IDENTIFIED BY 'wangqing123!';
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)
//查看指定用户wangqing的授权信息
mysql> SHOW GRANTS FOR wangqing;
+-----------------------------------------------+
| Grants for wangqing@% |
+-----------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'wangqing'@'%' |
+-----------------------------------------------+
1 row in set (0.00 sec)
mysql> SHOW GRANTS FOR 'wangqing'@'localhost';
+-------------------------------------------------------+
| Grants for wangqing@localhost |
+-------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'wangqing'@'localhost' |
+-------------------------------------------------------+
1 row in set (0.00 sec)
mysql> SHOW GRANTS FOR 'wangqing'@'127.0.0.1';
+-------------------------------------------------------+
| Grants for wangqing@127.0.0.1 |
+-------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'wangqing'@'127.0.0.1' |
+-------------------------------------------------------+
1 row in set (0.00 sec)
4.3.3 取消授权REVOKE
//语法:REVOKE priv_type,... ON db_name.table_name FROM 'username'@'host';
mysql> REVOKE ALL ON *.* FROM 'wangqing'@'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的服务进程重读授权表