mysql基础

mysql基础


常见的数据库有哪些?

关系型数据库:数据存放在硬盘当中

字段:每一列的第一行就是字段

记录:每一行代表一条记录

  • mysql 5.7之前都是开源 8.0开始商业化
  • mariadb
  • MSsql MicreSoft Sql
  • oracle 商业软件
  • sqlserver

非关系型数据库:数据存放在内存当中 变量 key=value

  • mongodb
  • redis
  • memcache

sqlite:数据存放在文件当中

关系型数据库介绍

数据结构模型

数据结构模型主要有:

  • 层次模型
  • 网状结构
  • 关系模型

关系模型:
二维关系:row,column

数据库管理系统:DBMS
关系:Relational,RDBMS

RDBMS专业名词

常见的关系型数据库管理系统:

  • MySQL:MySQL,MariaDB,Percona-Server
  • PostgreSQL:简称为pgsql
  • Oracle
  • MSSQL

**SQL:**Structure Query Language,结构化查询语言

**约束:**constraint,向数据表提供的数据要遵守的限制

  • 主键约束:一个或多个字段的组合,填入的数据必须能在本表中唯一标识本行。且必须提供数据,不能为空(NOT NULL)。
    • 一个表只能存在一个
  • 惟一键约束:一个或多个字段的组合,填入的数据必须能在本表中唯一标识本行。允许为空(NULL)
    • 一个表可以存在多个
  • 外键约束:一个表中的某字段可填入数据取决于另一个表的主键已有的数据
  • 检查性约束

**索引:**将表中的一个或多个字段中的数据复制一份另存,并且这些数据需要按特定次序排序存储

关系型数据库的常见组件

关系型数据库的常见组件有:

  • 数据库:database
  • 表:table,由行(row)和列(column)组成
  • 索引:index
  • 视图:view
  • 用户:user
  • 权限:privilege
  • 存储过程:procedure
  • 存储函数:function
  • 触发器:trigger
  • 事件调度器:event scheduler

SQL语句

SQL语句有三种类型:

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

mysql安装与配置

mysql安装方式有三种:

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

yum安装mysq

下载软件包
[root@localhost ~]# wget http://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm
--2022-07-25 13:41:19--  http://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm
Resolving dev.mysql.com (dev.mysql.com)... 23.13.191.247, 2600:140e:6:79d::2e31, 2600:140e:6:7a7::2e31

更新
[root@localhost ~]# rpm -Uvh mysql57-community-release-el7-11.noarch.rpm 
warning: mysql57-community-release-el7-11.noarch.rpm: Header V3 DSA/SHA1 Signature, key ID 5072e1f5: NOKEY
Verifying...                          ################################# [100%]
Preparing...                          ################################# [100%]
Updating / installing...
   1:mysql57-community-release-el7-11 ################################# [100%]
                                                             发现多了两个mysql的包
[root@localhost ~]# ls /etc/yum.repos.d/
mysql-community-source.repo  nginx-1.22.0.tar.gz
mysql-community.repo         yqz.repo
                                                              
 [root@localhost ~]# yum  module disable mysql
Failed to set locale, defaulting to C.UTF-8
MySQL Connectors Community                     47 kB/s |  49 kB     00:01    
MySQL Tools Community                         249 kB/s | 651 kB     00:02    
MySQL 5.7 Community Server                    1.0 MB/s | 2.6 MB     00:02    
Dependencies resolved.
==============================================================================
 Package           Architecture     Version           Repository         Size
==============================================================================
Disabling modules:
 mysql                                                                       

Transaction Summary
==============================================================================

Is this ok [y/N]: y
Complete!
                                                                        
                                                            
 
安装这三个包
[root@localhost ~]# yum -y install mysql-community-server mysql-community-client  mysql-community-common mysql-community-devel  --nogpgcheck --allowerasing
Failed to set locale, defaulting to C.UTF-8
Last metadata expiration check: 0:07:29 ago on Mon Jul 25 13:49:03 2022.
Dependencies resolved.
===============================================================================================
 Package                Arch   Version                                 Repository         Size
=============================================================================================
 
设置开机自启
[root@localhost ~]# systemctl enable --now mysqld
打开,查看状态
[root@localhost ~]# systemctl start mysqld.service
[root@localhost ~]# systemctl status mysqld
● mariadb.service - MariaDB 10.3 database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
   Active: active (running) since Mon 2022-07-25 13:28:44 CST; 39min ago
     Docs: man:mysqld(8)
                                     
查看端口号有3306
 [root@localhost ~]# ss -antl
State     Recv-Q     Send-Q         Local Address:Port         Peer Address:Port    Process    
LISTEN    0          128                  0.0.0.0:22                0.0.0.0:*                  
LISTEN    0          80                   0.0.0.0:3306              0.0.0.0:*                  
LISTEN    0          128                     [::]:22                   [::]:*                                
                                                             

yum安装mariadb

安装mariadb软件包
[root@localhost ~]# yum install -y mariadb*
Failed to set locale, defaulting to C.UTF-8
 perl-macros-4:5.26.3-421.el8.x86_64                                                          
  perl-parent-1:0.237-1.el8.noarch                                                             
  perl-podlators-4.11-1.el8.noarch                                                             
  perl-threads-1:2.21-2.el8.x86_64                                                             
  perl-threads-shared-1.58-2.el8.x86_64                                                                                
Complete!

开机自启
[root@localhost ~]# systemctl enable --now  mariadb
Created symlink /etc/systemd/system/mysql.service → /usr/lib/systemd/system/mariadb.service.
Created symlink /etc/systemd/system/mysqld.service → /usr/lib/systemd/system/mariadb.service.
Created symlink /etc/systemd/system/multi-user.target.wants/mariadb.service → /usr/lib/systemd/system/mariadb.service.

进入数据库
[root@localhost ~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 8
Server version: 10.3.28-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input stateme


设置一个密码
MariaDB [(none)]> set password = password('12345.com');
Query OK, 0 rows affected (0.000 sec)

登录
[root@localhost ~]# mysql -uroot -p12345.com
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 9
Server version: 10.3.28-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> 

mysql的程序组成

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

mysql工具使用

查看当前使用的mysql版本
[root@localhost ~]# mysql -V
mysql  Ver 15.1 Distrib 10.3.28-MariaDB, for Linux (x86_64) using readline 5.1

指定服务器主机,默认为localhost
[root@localhost ~]# mysql -uroot -p12345.com -hlocalhost
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 11
Server version: 10.3.28-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> 

 不登录mysql执行sql语句后退出,常用于脚本   
[root@localhost ~]# mysql -uroot -p  -e ' show databases;'
Enter password: 
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+

服务器监听的两种socket地址

socket类型说明
ip socket默认监听在tcp的3306端口,支持远程通信
unix sock监听在sock文件上(/tmp/mysql.sock,/var/lib/mysql/mysql.sock) 仅支持本地通信 server地址只能是:localhost,127.0.0.1

MySQL 数据类型

MySQL支持多种类型的SQL数据类型:数值,日期和时间类型,字符串(字符和字节)类型,空间类型和 JSON数据类型等

数值类型

数值类型包括整数型浮点型定点型

  • M表示整数类型的最大显示宽度。M表示整数类型的最大显示宽度。对于浮点和定点类型, M是可以存储的总位数(精度)。对于字符串类型, M是最大长度。允许的最大值M取决于数据类型。
  • D适用于浮点和定点类型,并指示小数点后面的位数。最大可能值为30,但不应大于 M-2。
  • 表示类型定义的可选部分。

在MySQL中常用数据类型主要分为以下几类

  • 数值类型
  • 字符串类型
  • 日期时间类型

整数型

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5o2KmEJf-1658821390589)(C:\Users\yz\Desktop\20180809112526190.png)]

在计算机中,可以区分正负的类型,称为有符号类型。无正负的类型,称为无符号类型。
简单的理解为就是
有符号值可以表示负数,0以及正数
无符号值只能为0或正数

字符串类型

  • CHAR[(M)] 一个固定长度的字符串,在存储时始终用空格填充指定长度。 M表示以字符为单位的列长度。M的范围为0到255.如果M省略,则长度为1,存储时占用M个字节
  • VARCHAR(M)可变长度的字符串,M 表示字符的最大列长度,M的范围是0到65,535,存储时占用**L+1(L<=M,L为实际字符的长度)**个字节
  • TINYTEXT[(M)] 不能有默认值,占用L+1个字节,L<2^8
  • TEXT[(M)] 不能有默认值,占用L+2个字节,L<2^16
  • MEDIUMTEXT[(M)] 不能有默认值,占用L+3个字节,L<2^24
  • LONGTEXT[(M)] 不能有默认值,占用L+4个字节,L<2^32
  • ENUM(‘value1’,‘value2’,…) ENUM是一个字符串对象,其值从允许值列表中选择,它只能有一个值,从值列表中选择,最多可包含65,535个不同的元素
  • SET(‘value1’,‘value2’,…) 字符串对象,该对象可以有零个或多个值,最多可包含64个不同的成员

日期时间类型

  • TIME 范围是’-838:59:59.000000’ 到’838:59:59.000000’
  • DATE 支持的范围是 '1000-01-01’到 ‘9999-12-31’
  • DATETIME 日期和时间组合。支持的范围是 '1000-01-01 00:00:00.000000’到 ‘9999-12-31 23:59:59.999999’。
  • TIMESTAMP 时间戳。范围是’1970-01-01 00:00:01.000000’UTC到’2038-01-19 03:14:07.999999’UTC。
  • YEAR 范围是 1901到2155

我们可以看到TIME的存储范围是’-838:59:59’到 ‘838:59:59’,因为TIME类型不仅可以用于表示一天中的时间(,还可以用于表示两个事件之间的经过时间或时间间隔

TIME的完整的显示为 D HH:MM:SS
D:表示天数,当指定该值时,存储时小时会先乘以该值
HH:表示小时
MM:表示分钟
SS:表示秒

mysql数据库操作

DDL操作

创建一个数据库
MariaDB [(none)]> create database if not exists yyyz;
Query OK, 1 row affected (0.000 sec)


查看当前实例有哪些数据库
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| yyyz               |
+--------------------+
4 rows in set (0.000 sec)

删除数据库
MariaDB [yyyz]> drop database yyyz
    -> ;
Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.000 sec)


创建表
MariaDB [yyyz]> create table yyz(id int not null,name varchar(10),age tinyint(2));
Query OK, 0 rows affected (0.006 sec)

查看当前数据库有哪些表
MariaDB [yyyz]> show tables;
+----------------+
| Tables_in_yyyz |
+----------------+
| yyz            |
+----------------+
1 row in set (0.000 sec)

删除表
MariaDB [yyyz]> drop table yyz;
Query OK, 0 rows affected (0.004 sec)

MariaDB [yyyz]> show tables;
Empty set (0.000 sec)




数据库用户创建
MariaDB [yyyz]> create user 'yyzz'@'192.168.17.146' identified by '12345.com';
Query OK, 0 rows affected (0.000 sec)

MariaDB [yyyz]> exit                                     
Bye

使用新创建的用户和密码登录
[root@localhost ~]# mysql -uyyzz -p12345.com -h192.168.17.146
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 21
Server version: 10.3.28-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> 


查看支持的所有字符集
MariaDB [(none)]> 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 |
.......
40 rows in set (0.000 sec)



查看当前数据库支持的所有存储引擎
MariaDB [(none)]> show engines;
+--------------------+---------+----------------------------------------------------------------------------------+--------------+------+------------+
| Engine             | Support | Comment                                                                          | Transactions | XA   | Savepoints |
+--------------------+---------+----------------------------------------------------------------------------------+--------------+------+------------+
| MEMORY             | YES     | Hash based, stored in memory, useful for temporary tables                        | NO           | NO   | NO         |
| MRG_MyISAM         | YES     | Collection of identical MyISAM tables                                            | NO           | NO   | NO         |
.......
12 rows in set (0.000 sec)


查看数据库信息
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
+--------------------+
1 row in set (0.000 sec)

不进入某数据库而列出其包含的所有表
MariaDB [yyyz]> show tables from yyyz;
+----------------+
| Tables_in_yyyz |
+----------------+
| yyz            |
+----------------+
1 row in set (0.000 sec)




查看表结构
MariaDB [yyyz]> desc yyyz.yyz;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   |     | NULL    |       |
| name  | varchar(10) | YES  |     | NULL    |       |
| age   | tinyint(2)  | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.001 sec)





查看yyz表的创建命令
MariaDB [yyyz]> show create table yyyz.yyz;
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                            |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------+
| yyz   | CREATE TABLE `yyz` (
  `id` int(11) NOT NULL,
  `name` varchar(10) DEFAULT NULL,
  `age` tinyint(2) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.000 sec)



查看yyz表的状态
MariaDB [yyyz]> show table status like 'yyz'\G
*************************** 1. row ***************************
            Name: yyz
          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: 2022-07-25 14:57:01
     Update_time: NULL
      Check_time: NULL
       Collation: latin1_swedish_ci
        Checksum: NULL
  Create_options: 
         Comment: 
Max_index_length: 0
       Temporary: N
1 row in set (0.001 sec)

获取帮助

获取创建表的帮助
MariaDB [yyyz]> help create table;
Name: 'CREATE TABLE'
Description:
Syntax:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    (create_definition,...)
    [table_options]
    [partition_options]

Or:

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
........

DML操作

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

INSERT语句
MariaDB [yyyz]> show tables
    -> ;
+----------------+
| Tables_in_yyyz |
+----------------+
| yyz            |
+----------------+
1 row in set (0.000 sec)


在yyz表格里插入数据
MariaDB [yyyz]> INSERT INTO yyz (id,name,age) VALUES (2,'jerry',23),(3,'yyzz',25),(4,'sean',28),(5,'zhangshan',26),(6,'zhangshan',20),(7,'lisi',NULL);
Query OK, 6 rows affected (0.002 sec)
Records: 6  Duplicates: 0  Warnings: 0


MariaDB [yyyz]> select * from yyz;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  2 | jerry     |   23 |
|  3 | yyzz      |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
|  7 | lisi      | NULL |
+----+-----------+------+
6 rows in set (0.000 sec)

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个结果
MariaDB [yyyz]> select * from yyz;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  2 | jerry     |   23 |
|  3 | yyzz      |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
|  7 | lisi      | NULL |
+----+-----------+------+
6 rows in set (0.000 sec)

只看名字
MariaDB [yyyz]> select name from yyz;
+-----------+
| name      |
+-----------+
| jerry     |
| yyzz      |
| sean      |
| zhangshan |
| zhangshan |
| lisi      |
+-----------+
6 rows in set (0.000 sec)


查看所有以年龄升序排列
MariaDB [yyyz]> select * from yyz order by age;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  7 | lisi      | NULL |
|  6 | zhangshan |   20 |
|  2 | jerry     |   23 |
|  3 | yyzz      |   25 |
|  5 | zhangshan |   26 |
|  4 | sean      |   28 |
+----+-----------+------+
6 rows in set (0.000 sec)



按年龄降序
MariaDB [yyyz]> select * from yyz order by age desc;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  3 | yyzz      |   25 |
|  2 | jerry     |   23 |
|  6 | zhangshan |   20 |
|  7 | lisi      | NULL |
+----+-----------+------+
6 rows in set (0.000 sec)





查看所有以年龄升序排列,展示前两条数据
MariaDB [yyyz]> select * from yyz order by age limit 2;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  7 | lisi      | NULL |
|  6 | zhangshan |   20 |
+----+-----------+------+
2 rows in set (0.000 sec)



查看所有以年龄升序排列,展示第二条和第三条两条数据
MariaDB [yyyz]> select * from yyz order by age limit 1,2;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  6 | zhangshan |   20 |
|  2 | jerry     |   23 |
+----+-----------+------+
2 rows in set (0.000 sec)

查看年龄大于等于25的所有数据
MariaDB [yyyz]> select * from yyz where age >=25;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  3 | yyzz      |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
+----+-----------+------+
3 rows in set (0.001 sec)


查看大于等于25 并叫zhangshan的数据
MariaDB [yyyz]> select * from yyz where age >= 25 and name  = 'zhangshan';
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  5 | zhangshan |   26 |
+----+-----------+------+
1 row in set (0.000 sec)



查看2328之间的数据
MariaDB [yyyz]> select * from yyz where age between  23 and 28;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  2 | jerry     |   23 |
|  3 | yyzz      |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
+----+-----------+------+
4 rows in set (0.001 sec)


查看年龄不为空的数据
MariaDB [yyyz]> select * from yyz where age is not null;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  2 | jerry     |   23 |
|  3 | yyzz      |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
+----+-----------+------+
5 rows in set (0.000 sec)


查看年龄空
MariaDB [yyyz]> select * from yyz where age is null;
+----+------+------+
| id | name | age  |
+----+------+------+
|  7 | lisi | NULL |
+----+------+------+
1 row in set (0.000 sec)

update语句
修改
MariaDB [yyyz]> select * from yyz;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  2 | jerry     |   23 |
|  3 | yyzz      |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
|  7 | lisi      | NULL |
+----+-----------+------+
6 rows in set (0.000 sec)




MariaDB [yyyz]> update yyz set age = 30 where name = 'lisi';
Query OK, 1 row affected (0.002 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [yyyz]> select * from yyz where name = 'lisi';
+----+------+------+
| id | name | age  |
+----+------+------+
|  7 | lisi |   30 |
+----+------+------+
1 row in set (0.000 sec)

delete语句
删除某条记录
MariaDB [yyyz]> delete from yyz where id = 7;
Query OK, 1 row affected (0.001 sec)

MariaDB [yyyz]> select * from yyz;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  2 | jerry     |   23 |
|  3 | yyzz      |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
+----+-----------+------+
5 rows in set (0.000 sec)


删除整张表的内容
MariaDB [yyyz]> delete from yyz;
Query OK, 5 rows affected (0.001 sec)

MariaDB [yyyz]> select  * from yyz;
Empty set (0.000 sec)

MariaDB [yyyz]> desc yyz;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   |     | NULL    |       |
| name  | varchar(10) | YES  |     | NULL    |       |
| age   | tinyint(2)  | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.002 sec)

truncate语句
语句类型特点
deleteDELETE删除表内容时仅删除内容,但会保留表结构 DELETE语句每次删除一行,并在事务日志中为所删除的每行记录一项 可以通过回滚事务日志恢复数据 非常占用空间
truncate删除表中所有数据,且无法恢复 表结构、约束和索引等保持不变,新添加的行计数值重置为初始值 执行速度比DELETE快,且使用的系统和事务日志资源少 通过释放存储表数据所用的数据页来删除数据,并且只在事务日志中记录页的释放 对于有外键约束引用的表,不能使用TRUNCATE TABLE删除数据 不能用于加入了索引视图的表
MariaDB [yyyz]> select * from yyz;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  2 | jerry     |   23 |
|  3 | yyzz      |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
|  7 | lisi      | NULL |
+----+-----------+------+
6 rows in set (0.000 sec)



MariaDB [yyyz]> truncate yyz;
Query OK, 0 rows affected (0.005 sec)

MariaDB [yyyz]> select * from yyz;
Empty set (0.000 sec)

MariaDB [yyyz]> desc yyz;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   |     | NULL    |       |
| name  | varchar(10) | YES  |     | NULL    |       |
| age   | tinyint(2)  | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.001 sec)


DCL操作

创建授权grant

权限类型(priv_type)

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

指定要操作的对象db_name.table_name

表示方式意义
.所有库的所有表
db_name指定库的所有表
db_name.table_name指定库的指定表
授权yyz用户在数据库本机上登录访问所有数据库
MariaDB [yyyz]> grant all on *.* to 'yyz'@'localhost' identified by '12345.com'
    -> ;
Query OK, 0 rows affected (0.000 sec)


MariaDB [yyyz]> grant all on *.* to 'yyz'@'192.168.17.146' identified by '12345.com';
Query OK, 0 rows affected (0.000 sec)


授权yyyz用户在192.168.17.146上远程登录访问yyz数据库
MariaDB [yyyz]> grant all on  yyyzz.* to 'yyz'@'192.168.17.146' identified by '12345.com';
Query OK, 0 rows affected (0.000 sec)

授权yyyz用户在所有位置上远程登录访问yyz数据库
MariaDB [yyyz]> GRANT ALL ON *.* TO 'yyz'@'%' IDENTIFIED BY '12345.com';
Query OK, 0 rows affected (0.000 sec)



查看授权
查看当前登录用户的授权信息
MariaDB [yyyz]> show grants;
+----------------------------------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost                                                                                                              |
+----------------------------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO `root`@`localhost` IDENTIFIED BY PASSWORD '*59AE2755EFB069A73FA8B830AF872B73013BAB5F' WITH GRANT OPTION |
| GRANT PROXY ON ''@'%' TO 'root'@'localhost' WITH GRANT OPTION                                                                          |
+----------------------------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.000 sec)

查看指定用户yyz的授权信息
MariaDB [yyyz]> show grants for yyz;
+-------------------------------------------------------------------------------------------------------------+
| Grants for yyz@%                                                                                            |
+-------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO `yyz`@`%` IDENTIFIED BY PASSWORD '*59AE2755EFB069A73FA8B830AF872B73013BAB5F' |
+-------------------------------------------------------------------------------------------------------------+
1 row in set (0.000 sec)



MariaDB [yyyz]> show grants for 'yyz'@'localhost';
+---------------------------------------------------------------------------------------------------------------------+
| Grants for yyz@localhost                                                                                            |
+---------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO `yyz`@`localhost` IDENTIFIED BY PASSWORD '*59AE2755EFB069A73FA8B830AF872B73013BAB5F' |
+---------------------------------------------------------------------------------------------------------------------+
1 row in set (0.000 sec)




MariaDB [yyyz]> show grants for 'yyz'@'192.168.17.146';
+--------------------------------------------------------------------------------------------------------------------------+
| Grants for yyz@192.168.17.146                                                                                            |
+--------------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO `yyz`@`192.168.17.146` IDENTIFIED BY PASSWORD '*59AE2755EFB069A73FA8B830AF872B73013BAB5F' |
| GRANT ALL PRIVILEGES ON `yyyzz`.* TO `yyz`@`192.168.17.146`                                                              |
+--------------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.000 sec)

取消授权REVOKE
MariaDB [yyyz]> revoke all on *.* from 'yyz'@'192.168.17.146';
Query OK, 0 rows affected (0.000 sec)


重读授权表
MariaDB [yyyz]> flush privileges;
Query OK, 0 rows affected (0.000 sec)


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

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

实战案例

1…创建一个以你名字为名的数据库,并创建一张表student,该表包含三个字段(id,name,age),表结构如下:

MariaDB [(none)]> create database yqz;
Query OK, 1 row affected (0.000 sec)

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| yqz                |
| yyyz               |
+--------------------+
5 rows in set (0.000 sec)

MariaDB [(none)]> use yqz;
Database changed
MariaDB [yqz]> create table student(id int not null primary key auto_increment,name varchar(100) not null,age tinyint(2));
Query OK, 0 rows affected (0.004 sec)

MariaDB [yqz]> desc student;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(100) | NO   |     | NULL    |                |
| age   | tinyint(2)   | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
3 rows in set (0.001 sec)

2.查看下该新建的表有无内容(用select语句)

MariaDB [yqz]> select * from student;
Empty set (0.000 sec)

3.往新建的student表中插入数据(用insert语句),结果应如下所示:

MariaDB [yqz]> insert student(id,name,age) values(1,'tom',20),(2,'jerry',23),(3,'yyz',25),(4,'sean',28),(5,'zhangshan',26),(6,'lisi',null),(7,'chenshuo',10),(8,'wangwu',3),(9,'qiuyi',15),(10,'yyyz',13),(11,'yqz',24);
Query OK, 11 rows affected (0.001 sec)
Records: 11  Duplicates: 0  Warnings: 0

MariaDB [yqz]> select * from student;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | tom       |   20 |
|  2 | jerry     |   23 |
|  3 | yyz       |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | lisi      | NULL |
|  7 | chenshuo  |   10 |
|  8 | wangwu    |    3 |
|  9 | qiuyi     |   15 |
| 10 | yyyz      |   13 |
| 11 | yqz       |   24 |
+----+-----------+------+
11 rows in set (0.000 sec)

4.修改lisi的年龄为50

MariaDB [yqz]> update student set age = 50 where name = 'lisi';
Query OK, 1 row affected (0.001 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [yqz]> select * from student where name = 'lisi';
+----+------+------+
| id | name | age  |
+----+------+------+
|  6 | lisi |   50 |
+----+------+------+
1 row in set (0.000 sec)

5.以age字段降序排序

MariaDB [yqz]> select * from student order by age desc;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  6 | lisi      |   50 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  3 | yyz       |   25 |
| 11 | yqz       |   24 |
|  2 | jerry     |   23 |
|  1 | tom       |   20 |
|  9 | qiuyi     |   15 |
| 10 | yyyz      |   13 |
|  7 | chenshuo  |   10 |
|  8 | wangwu    |    3 |
+----+-----------+------+
11 rows in set (0.000 sec)

6.查询student表中年龄最小的3位同学跳过前2位

MariaDB [yqz]> select * from student order by age limit 2,3;
+----+-------+------+
| id | name  | age  |
+----+-------+------+
| 10 | yyyz  |   13 |
|  9 | qiuyi |   15 |
|  1 | tom   |   20 |
+----+-------+------+
3 rows in set (0.000 sec)

7.查询student表中年龄最大的4位同学

MariaDB [yqz]> select * from student order by age desc limit 4;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  6 | lisi      |   50 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  3 | yyz       |   25 |
+----+-----------+------+
4 rows in set (0.000 sec)

MariaDB [yqz]> select * from student order by age desc;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  6 | lisi      |   50 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  3 | yyz       |   25 |
| 11 | yqz       |   24 |
|  2 | jerry     |   23 |
|  1 | tom       |   20 |
|  9 | qiuyi     |   15 |
| 10 | yyyz      |   13 |
|  7 | chenshuo  |   10 |
|  8 | wangwu    |    3 |
+----+-----------+------+
11 rows in set (0.000 sec)

8.查询student表中名字叫zhangshan的记录

MariaDB [yqz]> select * from student where name = 'zhangshan';
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  5 | zhangshan |   26 |
+----+-----------+------+
1 row in set (0.000 sec)

9.查询student表中名字叫zhangshan且年龄大于20岁的记录

MariaDB [yqz]> select * from student where name = 'zhangshan' and age > 20;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  5 | zhangshan |   26 |
+----+-----------+------+
1 row in set (0.000 sec)

10.查询student表中年龄在23到30之间的记录

MariaDB [yqz]> select * from student where age between 23 and 30;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  2 | jerry     |   23 |
|  3 | yyz       |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
| 11 | yqz       |   24 |
+----+-----------+------+
5 rows in set (0.000 sec)

11.修改wangwu的年龄为100

MariaDB [yqz]> update student set age = 100 where name = 'wangwu';
Query OK, 1 row affected (0.001 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [yqz]> select * from student where name = 'wangwu';
+----+--------+------+
| id | name   | age  |
+----+--------+------+
|  8 | wangwu |  100 |
+----+--------+------+
1 row in set (0.000 sec)

12.删除student中名字叫zhangshan且年龄小于等于20的记录

```javascript
MariaDB [yqz]> delete from student where name = 'zhangshan' and age >= 20;
Query OK, 1 row affected (0.001 sec)

MariaDB [yqz]> select * from student;
+----+----------+------+
| id | name     | age  |
+----+----------+------+
|  1 | tom      |   20 |
|  2 | jerry    |   23 |
|  3 | yyz      |   25 |
|  4 | sean     |   28 |
|  6 | lisi     |   50 |
|  7 | chenshuo |   10 |
|  8 | wangwu   |  100 |
|  9 | qiuyi    |   15 |
| 10 | yyyz     |   13 |
| 11 | yqz      |   24 |
+----+----------+------+


10 rows in set (0.000 sec)
+----+-----------+------+
|  2 | jerry     |   23 |
|  3 | yyz       |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
| 11 | yqz       |   24 |
+----+-----------+------+
5 rows in set (0.000 sec)

11.修改wangwu的年龄为100

MariaDB [yqz]> update student set age = 100 where name = 'wangwu';
Query OK, 1 row affected (0.001 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [yqz]> select * from student where name = 'wangwu';
+----+--------+------+
| id | name   | age  |
+----+--------+------+
|  8 | wangwu |  100 |
+----+--------+------+
1 row in set (0.000 sec)

12.删除student中名字叫zhangshan且年龄小于等于20的记录

```javascript
MariaDB [yqz]> delete from student where name = 'zhangshan' and age >= 20;
Query OK, 1 row affected (0.001 sec)

MariaDB [yqz]> select * from student;
+----+----------+------+
| id | name     | age  |
+----+----------+------+
|  1 | tom      |   20 |
|  2 | jerry    |   23 |
|  3 | yyz      |   25 |
|  4 | sean     |   28 |
|  6 | lisi     |   50 |
|  7 | chenshuo |   10 |
|  8 | wangwu   |  100 |
|  9 | qiuyi    |   15 |
| 10 | yyyz     |   13 |
| 11 | yqz      |   24 |
+----+----------+------+
10 rows in set (0.000 sec)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值