mysql基础

mysql基础

1.mysql 简介

1.1 MySQL介绍

MySQL是一个精巧的SQL数据库管理系统,虽然它不是开放源代码的产品,但在某些情况下你可以自由使用。由于它的强大功能、灵活性、丰富的应用编程接口(API)以及精巧的系统结构,受到了广大自由软件爱好者甚至是商业软件用户的青睐,特别是与Apache和PHP/PERL结合,为建立基于数据库的动态网站提供了强大动力。

1.2 MySQL的特点与作用

MySQL是一个真正的多用户、多线程SQL数据库服务器。SQL(结构化查询语言)是世界上最流行的和标准化的数据库语言。MySQL是以一个客户机/服务器结构的实现,它由一个服务器守护程序mysqld和很多不同的客户程序和库组成。

SQL是一种标准化的语言,它使得存储、更新和存取信息更容易。例如,你能用SQL语言为一个网站检索产品信息及存储顾客信息,同时MySQL也足够快和灵活以允许你存储记录文件和图像。

MySQL数据库的主要功能只在组织和管理很庞大或复杂的信息和基于WEB的库存查询请求不仅仅为客户提供信息,而且还可以为您自己使用数据库可以提供如下功能:

  1. 减少记录编档的时间
  2. 减小记录检索时间
  3. 灵活的查找序列
  4. 灵活的输出格式
  5. 多个用户同时访问记录

1.3 SQL语句

SQL语句有三种类型:

  • DDL:Data Defination Language,数据定义语言
  • DML:Data Manipulation Language,数据操纵语言
  • DCL:Data Control Language,数据控制语言
SQL语句的类型对应的操作
DDLCREATE:创建, DROP:删除 , ALTER:修改
DMLINSERT:向表中插入数据,DELETE:删除表中数据,UPDATE:更新表中数据,SELECT:查询表中数据
DCLGRANT:授权,REVOKE:移除授权

2.mysql安装与配置

2.1 mysql安装

mysql安装方式有三种:

  • 源代码:编译安装
  • 二进制格式的程序包:展开至特定路径,并经过简单配置后即可使用
  • 程序包管理器管理的程序包:
    rpm:有两种
    1. OS Vendor:操作系统发行商提供的
    2.项目官方提供的

2.2 MySQL配置

# 配置mysql的yum源
[root@100 src]# wget http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm
[root@100 src]# ls
mysql57-community-release-el7-10.noarch.rpm

[root@100 src]# yum -y install mysql57-community-release-el7-10.noarch.rpm
[root@100 ~]# cd /etc/yum.repos.d/
[root@100 yum.repos.d]# ls
mysql-community.repo  mysql-community-source.repo  redhat.repo  ss.repo

# 安装mysql5.7
[root@100 yum.repos.d]#  yum -y install mysql-community-server mysql-community-client mysql-community-common mysql-community-devel
安装过程略。。。

# 启动mysql
[root@100 ~]# systemctl start mysqld
[root@100 ~]# systemctl status mysqld
● mysqld.service - MySQL Server
   Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
   Active: active (running) since 五 2019-07-05 21:28:31 CST; 5s ago

# 查看3306端口是否启动
[root@100 ~]# ss -antl
State       Recv-Q Send-Q      Local Address:Port                     Peer Address:Port              
LISTEN      0      50                      *:139                                 *:*                  
LISTEN      0      128                     *:111                                 *:*                  
LISTEN      0      128                     *:22                                  *:*                  
LISTEN      0      100             127.0.0.1:25                                  *:*                  
LISTEN      0      50                      *:445                                 *:*                  
LISTEN      0      128                     *:44643                               *:*                                      
LISTEN      0      80                     :::3306                               :::*   

# 在日志文件中找出临时密码
[root@100 ~]# grep "password" /var/log/mysqld.log
2019-07-05T13:28:28.423984Z 1 [Note] A temporary password is generated for root@localhost: )ojUe:V7PR=:
# 临时密码为:   )ojUe:V7PR=:

# 使用临时密码登录MySQL
[root@100 ~]# 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.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>             // 看到有这样的标识符则表示成功登录了



# 修改mysql登录密码(两种方式)
1.
mysql> set global validate_password_policy=0;
Query OK, 0 rows affected (0.01 sec)

mysql> set global validate_password_length=1;
Query OK, 0 rows affected (0.00 sec)

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'Shicailun123!';
Query OK, 0 rows affected (0.01 sec)

mysql> quit                 //修改成功后退出

2.
[root@100 ~]# mysql_secure_installation
Enter password for user root:                  //此处输入现密码
Change the password for root ? ((Press y|Y for Yes, any other key for No) : yes    //此处回答yes,修改根密码
New password:                   //输入新密码
Re-enter new password:      //再次输入新密码
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : yes    //是否继续使用提供的密码,yes
Remove anonymous users? (Press y|Y for Yes, any other key for No) : yes          //删除匿名用户yes
Disallow root login remotely? (Press y|Y for Yes, any other key for No) : yes         //不允许root用户登录
Remove test database and access to it? (Press y|Y for Yes, any other key for No) : yes         //删除测试数据库并访问它
Reload privilege tables now? (Press y|Y for Yes, any other key for No) : yes     //立即重新加载特权表
Success.

All done!                //修改成功
[root@100 ~]# 

# 为避免mysql自动升级,这里需要卸载最开始安装的yum源
[root@100 ~]# rpm -qa|grep mysql
mysql57-community-release-el7-10.noarch
mysql-community-client-5.7.26-1.el7.x86_64
mysql-community-libs-5.7.26-1.el7.x86_64
mysql-community-server-5.7.26-1.el7.x86_64
mysql-community-devel-5.7.26-1.el7.x86_64
mysql-community-common-5.7.26-1.el7.x86_64
mysql-community-libs-compat-5.7.26-1.el7.x86_64
[root@100 ~]# yum -y remove mysql57-community-release-el7-10.noarch      //卸载主包

3. mysql的程序组成

客户端:

  • mysql:CLI交互式客户端程序
  • mysql_secure_installation:安全初始化,强烈建议安装完以后执行此命令
  • mysqldump:mysql备份工具
  • mysqladmin

服务器端:

  • mysqld

3.1mysql工具使用

# 语法:mysql [OPTIONS] [database]
# 常用的OPTIONS:
    -uUSERNAME      //指定用户名,默认为root
    -hHOST          //指定服务器主机,默认为localhost,推荐使用ip地址
    -pPASSWORD      //指定用户的密码
    -P#             //指定数据库监听的端口,这里的#需用实际的端口号代替,如-P3307
    -V              //查看当前使用的mysql版本
    -e              //不登录mysql执行sql语句后退出,常用于脚本

# 客户机登录服务端的mysql服务器需要下载mariadb
[root@96 ~]# yum -y install mariadb
[root@96 ~]# mysql -uroot -pSHIcailun123! -h192.168.100.100

[root@100 ~]# mysql -V
mysql  Ver 14.14 Distrib 5.7.26, for Linux (x86_64) using  EditLine wrapper

[root@100 ~]# mysql -uroot -p -h 127.0.0.1 -e 'SHOW DATABASES;'
Enter password: 
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
[root@100 ~]# 

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
# 使用sock文件可以直接登录mysql
[root@100 ~]# mysql -S /var/lib/mysql/mysql.sock -h127.0.0.1 -pSHIcailun123!
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 12
Server version: 5.7.26 MySQL Community Server (GPL)

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> 

3.3 mysql 的数据类型

3.3.1 数值型

MySQL支持所有标准SQL数值数据类型。

这些类型包括严格数值数据类型(INTEGER、SMALLINT、DECIMAL和NUMERIC),以及近似数值数据类型(FLOAT、REAL和DOUBLE PRECISION)。

关键字INT是INTEGER的同义词,关键字DEC是DECIMAL的同义词。

BIT数据类型保存位字段值,并且支持MyISAM、MEMORY、InnoDB和BDB表。

作为SQL标准的扩展,MySQL也支持整数类型TINYINT、MEDIUMINT和BIGINT。下面的表显示了需要的每个整数类型的存储和范围。

类型大小范围(有符号)范围(无符号)用途
TINYINT1字节(-128,127)(0,255)小整数值
SMALLINT2字节(-32 768,32 767)(0,65535)大整数值
MEDIUMINT3字节(-8 388 608,8 388 607)(0,16777215)大整数值
INT或INTEGER4字节(-2 147 483 648,2 147 483 647)(0,4 294 967 295)大整数值
BIGINT8字节(-9 233 372 036 854 775 808,9 223 372 036 854 775 807)(0,18 446 744 073 709 551 615)极大整数值
DOUBLE8字节(-1.797 693 134 862 315 7 E+308,-2.225 073 858 507 201 4 E-308),
0,
(2.225 073 858 507 201 4 E-308,1.797 693 134 862 315 7 E+308)
0,(2.225 073 858 507 201 4 E-308,1.797 693 134 862 315 7 E+308)小数值
3.3.2 日期和时间类型

表示时间值的日期和时间类型为DATETIME、DATE、TIMESTAMP、TIME和YEAR。

每个时间类型有一个有效值范围和一个"零"值,当指定不合法的MySQL不能表示的值时使用"零"值。

类型大小( bytes)范围格式用途
DATE31000-01-01/9999-12-31YYYY-MM-DD日期值
TIME3‘-838:59:59’/‘838:59:59’HH:MM:SS时间值或持续时间
YEAR11901/2155YYYY年份值
DATETIME81000-01-01 00:00:00/9999-12-31 23:59:59YYYY-MM-DD HH:MM:SS混合日期和时间值
TIMESTAMP41970-01-01 00:00:00/2038
结束时间是第 2147483647 秒,北京时间 2038-1-19 11:14:07,
格林尼治时间 2038年1月19日 凌晨 03:14:07
YYYYMMDD HHMMSS混合日期和时间值,时间戳
3.3.3 字符串类型

字符串类型指CHAR、VARCHAR、BINARY、VARBINARY、BLOB、TEXT、ENUM和SET。该节描述了这些类型如何工作以及如何在查询中使用这些类型。

类型大小用途
CHAR0-255 bytes定长字符串
VARCHAR0-65535 bytes变长字符串
TINYBLOB0-255 bytes不超过 255 个字符的二进制字符串
TINYTEXT0-255 bytes短文本字符串
BLOB0-65 535 bytes二进制形式的长文本数据
TEXT0-65 535 bytes长文本数据
MEDIUMBLOB0-16 777 215 bytes二进制形式的中等长度文本数据
MEDIUMTEXT0-16 777 215 bytes中等长度文本数据
LONGBLOB0-4 294 967 295 bytes二进制形式的极大文本数据
LONGTEXT0-4 294 967 295 bytes极大文本数据

注意: char(n) 和 varchar(n) 中括号中 n 代表字符的个数,并不代表字节个数,比如 CHAR(30) 就可以存储 30 个字符。

CHAR 和 VARCHAR 类型类似,但它们保存和检索的方式不同。它们的最大长度和是否尾部空格被保留等方面也不同。在存储或检索过程中不进行大小写转换。

BINARY 和 VARBINARY 类似于 CHAR 和 VARCHAR,不同的是它们包含二进制字符串而不要非二进制字符串。也就是说,它们包含字节字符串而不是字符字符串。这说明它们没有字符集,并且排序和比较基于列值字节的数值值。

BLOB 是一个二进制大对象,可以容纳可变数量的数据。有 4 种 BLOB 类型:TINYBLOB、BLOB、MEDIUMBLOB 和 LONGBLOB。它们区别在于可容纳存储范围不同。

有 4 种 TEXT 类型:TINYTEXT、TEXT、MEDIUMTEXT 和 LONGTEXT。对应的这 4 种 BLOB 类型,可存储的最大长度不同,可根据实际情况选择。


4.mysql数据库操作

4.1 DDL操作

4.1.1 数据库操作
# 创建数据库
# 语法:CREATE DATABASE [IF NOT EXISTS] 'DB_NAME';
# 创建数据库whell
mysql> CREATE DATABASE whell;
Query OK, 1 row affected (0.00 sec)

# 查看当前有哪些数据库
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| whell              |
+--------------------+
5 rows in set (0.00 sec)


# 删除数据库
# 语法:DROP DATABASE [IF EXISTS] 'DB_NAME';
# 删除数据库whell
mysql> drop database whell;
Query OK, 0 rows affected (0.01 sec)

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

4.1.2 表操作
# 创建表
# 语法:CREATE TABLE table_name (col1 datatype 修饰符,col2 datatype 修饰符) ENGINE='存储引擎类型';
# 在数据库whell里创建表gailun
mysql> create database whell;           //先创建数据库whell
Query OK, 1 row affected (0.00 sec)

mysql> use whell          //进入whell数据库
Database changed

mysql> create table gailun(id int not null,name varchar(50) not null,age tinyint null);          //创建表gailun
Query OK, 0 rows affected (0.02 sec
# create table 为创建表,gailun为表名,id为第一个字段  int为整数 not null不能为空,name为第二字段 varchar(50)不能超过50个字符 not null不能为空,age为第三个字段 tinyint为整数(小整数值) ,null表示可以为空

# 查看当前数据库有哪些表
mysql> show tables;
+-----------------+
| Tables_in_whell |
+-----------------+
| gailun          |
+-----------------+
1 row in set (0.00 sec)

# 删除表
# 语法:DROP TABLE [ IF EXISTS ] 'table_name';
# 删除表gailun
mysql> drop table gailun;
Query OK, 0 rows affected (0.07 sec)

mysql> show tables;
Empty set (0.00 sec)

4.1.3 用户操作

mysql用户帐号由两部分组成,如’USERNAME’@‘HOST’,表示此USERNAME只能从此HOST上远程登录

这里(‘USERNAME’@‘HOST’)的HOST用于限制此用户可通过哪些主机远程连接mysql程序,其值可为:

  • IP地址
  • 通配符
    %:匹配任意长度的任意字符,常用于设置允许从任何主机登录
    _ :匹配任意单个字符
# 数据库用户创建
# 语法:CREATE USER 'username'@'host' [IDENTIFIED BY 'password'];
# 创建数据库用户scl
mysql> create user 'scl'@'192.168.100.100' identified by 'shicailun123!';
Query OK, 0 rows affected (0.01 sec)

# 使用新创建的用户和密码登录
[root@100 ~]# mysql -uscl -pshicailun123! -h192.168.100.100
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: 5.7.26 MySQL Community Server (GPL)

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> 

# 删除数据库用户
# 语法:DROP USER 'username'@'host'; 
mysql> DROP USER 'scl'@'192.168.100.100';       //需要在root身份下
Query OK, 0 rows affected (0.00 sec)
4.1.4 查看命令SHOW
mysql> SHOW CHARACTER SET;      //查看支持的所有字符集
mysql> SHOW ENGINES;        //查看当前数据库支持的所有存储引擎

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

# 不进入某数据库而列出其包含的所有表
mysql> use mysql;    //退出当前数据库
mysql> show tables from whell;
+-----------------+
| Tables_in_whell |
+-----------------+
| gailun          |
+-----------------+
1 row in set (0.00 sec)

# 查看表结构
# 语法:DESC [db_name.]table_name;
mysql> desc whell.gailun;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   |     | NULL    |       |
| name  | varchar(50) | NO   |     | NULL    |       |
| age   | tinyint(4)  | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

# 查看某表的创建命令
# 语法:SHOW CREATE TABLE db_name.table_name;
mysql> show create table whell.gailun;
+--------+--------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table  | Create Table                                                                                                                                           |
+--------+--------------------------------------------------------------------------------------------------------------------------------------------------------+
| gailun | CREATE TABLE `gailun` (
  `id` int(11) NOT NULL,
  `name` varchar(50) 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 whell           //进入whell数据库
Database changed
mysql> show table status like 'gailun'\G      //查看gailun这个表的状态
*************************** 1. row ***************************
           Name: gailun
         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: 2019-07-05 23:43:35
    Update_time: NULL
     Check_time: NULL
      Collation: latin1_swedish_ci
       Checksum: NULL
 Create_options: 
        Comment: 
1 row in set (0.00 sec)


# 获取帮助
# 获取命令使用帮助
# 语法:HELP keyword;
mysql> help create table;           //获取创建表的帮助
帮助信息略。。。。

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 whell;         # 进入whell数据库
Database changed
mysql> insert into gailun (id,name,age) value (1,'chenxi',50);           # 一次插入一条记录
Query OK, 1 row affected (0.01 sec)
mysql> insert into gailun (id,name,age) values (2,'fangfan',23),(3,'luyueda',25),(4,'chengsong',28),(5,'luoxianguang',36);   # 一次插入多条记录
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0
mysql> select * from gailun;      # 查看插入的表信息
+----+--------------+------+
| id | name         | age  |
+----+--------------+------+
|  1 | chenxi       |   50 |
|  1 | chenxi       |   50 |
|  2 | fangfan      |   23 |
|  3 | luyueda      |   25 |
|  4 | chengsong    |   28 |
|  5 | luoxianguang |   36 |
+----+--------------+------+
8 rows in set (0.00 sec)

4.2.2 SELECT语句

字段column表示法

表示符代表什么?
*所有字段
as字段别名,如col1 AS alias1当表名很长时用别名代替
mysql> select name as n,age from gailun;     //给name添加别名为n
+--------------+------+
| n            | age  |
+--------------+------+
| chenxi       |   50 |
| fangfan      |   23 |
| luyueda      |   25 |
| chengsong    |   28 |
| luoxianguang |   36 |
+--------------+------+
8 rows in set (0.00 sec)

条件判断语句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 gailun;      # 查看gailun这个表中的所有信息
+----+--------------+------+
| id | name         | age  |
+----+--------------+------+
|  1 | chenxi       |   50 |
|  2 | fangfan      |   23 |
|  3 | luyueda      |   25 |
|  4 | chengsong    |   28 |
|  5 | luoxianguang |   36 |
+----+--------------+------+
8 rows in set (0.00 sec)

mysql> select name from gailun;       # 只看name这个字段
+--------------+ 
| name         |
+--------------+
| chenxi       |
| fangfan      |
| luyueda      |
| chengsong    |
| luoxianguang |
+--------------+
8 rows in set (0.00 sec)

mysql> select name,age from gailun;    # 只看name和age这两个字段
+--------------+------+
| name         | age  |
+--------------+------+
| chenxi       |   50 |
| fangfan      |   23 |
| luyueda      |   25 |
| chengsong    |   28 |
| luoxianguang |   36 |
+--------------+------+
5 rows in set (0.00 sec)

# as别名
mysql> select name as n,age from gailun;     # 将name用别名n代替
+--------------+------+
| n            | age  |
+--------------+------+
| chenxi       |   50 |
| fangfan      |   23 |
| luyueda      |   25 |
| chengsong    |   28 |
| luoxianguang |   36 |
+--------------+------+
5 rows in set (0.00 sec)

mysql> select name,age from gailun where age >=30;   # 只看age大于等于30的
+--------------+------+
| name         | age  |
+--------------+------+
| chenxi       |   50 |
| luoxianguang |   36 |
+--------------+------+
2 rows in set (0.00 sec)

mysql> select name,age from gailun where age between 10 and 30; # 找age在10到30之间的
+-----------+------+
| name      | age  |
+-----------+------+
| fangfan   |   23 |
| luyueda   |   25 |
| chengsong |   28 |
+-----------+------+
3 rows in set (0.01 sec)

# like的用法
mysql> select * from gailun where name like 'luo%';
+----+--------------+------+
| id | name         | age  |
+----+--------------+------+
|  5 | luoxianguang |   36 |
+----+--------------+------+
1 row in set (0.00 sec)

 

# rlike 用法使用正则表达式
mysql> select * from gailun where name rlike 'ch*';
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | chenxi    |   50 |
|  4 | chengsong |   28 |
+----+-----------+------+
2 rows in set (0.00 sec)



mysql>  select * from gailun where age is null;   //找出表中age为空的字段
Empty set (0.00 sec)
												//此表没有空的所以没有显示

# and用法
mysql> select * from gailun where age=28 and name='chengsong';
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  4 | chengsong |   28 |
+----+-----------+------+
1 row in set (0.00 sec)

# or用法
mysql> select * from gailun where age=28 or name='chenxi';
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | chenxi    |   50 |
|  4 | chengsong |   28 |
+----+-----------+------+
2 rows in set (0.00 sec)

# not用法
# mysql> select * from gailun where age is not null;
+----+--------------+------+
| id | name         | age  |
+----+--------------+------+
|  1 | chenxi       |   50 |
|  2 | fangfan      |   23 |
|  3 | luyueda      |   25 |
|  4 | chengsong    |   28 |
|  5 | luoxianguang |   36 |
+----+--------------+------+
5 rows in set (0.00 sec)

# order升序排序
mysql> select * from gailun order by age;   # 按age字段升序排序
+----+--------------+------+
| id | name         | age  |
+----+--------------+------+
|  2 | fangfan      |   23 |
|  3 | luyueda      |   25 |
|  4 | chengsong    |   28 |
|  5 | luoxianguang |   36 |
|  1 | chenxi       |   50 |
+----+--------------+------+
5 rows in set (0.00 sec)

# 倒序排序
mysql> select * from gailun order by age desc;  # 按age字段倒序排序
+----+--------------+------+
| id | name         | age  |
+----+--------------+------+
|  1 | chenxi       |   50 |
|  5 | luoxianguang |   36 |
|  4 | chengsong    |   28 |
|  3 | luyueda      |   25 |
|  2 | fangfan      |   23 |
+----+--------------+------+
5 rows in set (0.00 sec)


mysql> select * from gailun order by age limit 2;   # 根据age升序排序取出前两个
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  2 | fangfan |   23 |
|  3 | luyueda |   25 |
+----+---------+------+
2 rows in set (0.00 sec)

# 根据age进行升序排序,并且略过第1个结果取后面的2个结果
mysql> select * from gailun order by age limit 1,2;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  3 | luyueda   |   25 |
|  4 | chengsong |   28 |
+----+-----------+------+
2 rows in set (0.00 sec)

4.2.3 update语句
mysql> update gailun set age = 50 where name = 'luyueda';     # 修改表里面name=luyueda的age=50
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select *from gailun;
+----+--------------+------+
| id | name         | age  |
+----+--------------+------+
|  1 | chenxi       |   50 |
|  2 | fangfan      |   23 |
|  3 | luyueda      |   50 |		# 此处改为了50
|  4 | chengsong    |   28 |
|  5 | luoxianguang |   36 |
+----+--------------+------+
5 rows in set (0.01 sec)

4.2.4 delete语句
mysql> delete from gailun where id=5;     # 删除表中id=5的一条内容
Query OK, 1 row affected (0.01 sec)

mysql> select * from gailun;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | chenxi    |   50 |
|  2 | fangfan   |   23 |
|  3 | luyueda   |   50 |
|  4 | chengsong |   28 |
+----+-----------+------+
4 rows in set (0.00 sec)


mysql> delete from gailun;        # 删除整张表的内容
4.2.5 truncate语句

truncate与delete的区别:

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

mysql> select * from gailun;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | chenxi    |   50 |
|  2 | fangfan   |   23 |
|  3 | luyueda   |   50 |
|  4 | chengsong |   28 |
+----+-----------+------+
4 rows in set (0.00 sec)

mysql> truncate gailun;                # 删除gailun这张表
Query OK, 0 rows affected (0.07 sec)

mysql> select * from gailun; 
Empty set (0.00 sec)                  # 表内容已经清空

mysql> desc gailun;          # 查看表结构,表结构还在
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   |     | NULL    |       |
| name  | varchar(50) | NO   |     | NULL    |       |
| age   | tinyint(4)  | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> 

4.3 DCL操作

4.3.1 创建授权grant
权限类型代表什么
ALL所有权限
SELECT读取内容权限
UPDATE更新内容的权限
DELETE删除内容的权限
INSERT插入内容的权限

指定要操作的对象db_name.table_name

表达方式意义
*.*所有库的所有表
db_name指定库的所有表
db_name.table_name指定库的指定表
# 授权scl用户在数据库本机上登录访问所有数据库
mysql> GRANT ALL ON *.* TO 'scl'@'localhost' IDENTIFIED BY 'shicailun!';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> GRANT ALL ON *.* TO 'scl'@'127.0.0.1' IDENTIFIED BY 'shicailun123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)

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

# 授权scl用户在所有位置上远程登录访问whell数据库
mysql> GRANT ALL ON whell.* TO 'scl'@'%' IDENTIFIED BY 'shicailun123!';
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)


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

mysql> SHOW GRANTS FOR 'scl'@'localhost';


mysql> SHOW GRANTS FOR 'scl'@'127.0.0.1';



4.3.3 取消授权REVOKE
# 语法:REVOKE priv_type,... ON db_name.table_name FROM 'username'@'host';

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

mysql> FLUSH PRIVILEGES;	    # 重读授权表(对权限进行添加,删除,修改后需要执行的命令)
Query OK, 0 rows affected (0.00 sec)


mysql系统密码破解

[root@96 ~]# echo 'skip-grant-tables' >>/etc/my.cnf	
[root@96 ~]# cat /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
port = 3306
pid-file = /opt/data/mysql.pid
user = mysql
skip-name-resolve
skip-grant-tables

# 重启服务
[root@96 ~]# service mysqld restart
Shutting down MySQL.. SUCCESS! 
Starting MySQL. SUCCESS!

[root@96 ~]# mysql -uroot
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.22 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数据库
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密码
mysql> update user set authentication_string = password('shicailun666!') where User = 'root';
Query OK, 1 row affected, 1 warning (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 1

mysql> quit
Bye

# 将配置文件中skip-grant-tables这一行删掉
[root@96 ~]# sed -i 's#skip-grant-tables# #g' /etc/my.cnf
[root@96 ~]# cat /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql
datadir = /opt/data
socket = /tmp/mysql.sock
port = 3306
pid-file = /opt/data/mysql.pid
user = mysql
skip-name-resolve

# 重启服务
[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.22 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> 



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值