关系型数据库介绍与mysql使用

1. 关系型数据库介绍

##1.1 数据结构模型

数据结构模型主要有:

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

关系模型:
二维关系:row,column(行与列)

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

关系型数据库的优点:

数据以表格的形式存储容易理解
支持SQL语言使用方便
易于维护
事务的一致性。

关系型数据库的缺点:

为了维护一致性所付出的巨大代价就是其读写性能比较差;
高并发读写效率较低;
海量数据的读写效率低;
固定的表结构。

关系型数据库举例:MySQL、Oracle、DB2、Microsoft SQL Server、SQLite等。

除了关系型数据库之外的数据库我们统称为:非关系型数据库(NoSQL)

1.2 RDBMS专业名词

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

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

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

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

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

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

1.3 关系型数据库的常见组件

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

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

1.4 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:有两种
    • OS Vendor:操作系统发行商提供的
      • 项目官方提供的
  • deb
    以centos7为例(不需要配置yum源)
[root@localhost ~]# yum -y install mariadb mariadb-server
BDB2053 Freeing read locks for locker 0x1a90: 103640/140014678771520
BDB2053 Freeing read locks for locker 0x1a92: 103640/140014678771520
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirrors.163.com
 * epel: mirror.sjtu.edu.cn
 * extras: mirrors.ustc.edu.cn
 * updates: mirrors.ustc.edu.cn
Resolving Dependencies
--> Running transaction check
---> Package mariadb.x86_64 1:5.5.68-1.el7 will be installed
--> Processing Dependency: mariadb-libs(x86-64) = 1:5.5.68-1.el7 for package: 1:mariadb-5.5.68-1.el7.x86_64
[root@localhost ~]# systemctl enable --now mariadb.service #设置开机自启
Created symlink from /etc/systemd/system/multi-user.target.wants/mariadb.service to /usr/lib/systemd/system/mariadb.service.
[root@localhost ~]# 
[root@localhost ~]# 
[root@localhost ~]# ss -antl # 3306为默认端口号
State      Recv-Q Send-Q    Local Address:Port                   Peer Address:Port              
LISTEN     0      50                    *:3306                              *:*                  
LISTEN     0      128                   *:111                               *:*                  
LISTEN     0      5         192.168.122.1:53                                *:*                  
LISTEN     0      128                   *:22                                *:*                  
LISTEN     0      128           127.0.0.1:631                               *:*                  
LISTEN     0      100           127.0.0.1:25                                *:*                  
LISTEN     0      128                  :::111                              :::*                  
LISTEN     0      128                  :::22                               :::*                  
LISTEN     0      128                 ::1:631                              :::*                  
LISTEN     0      100                 ::1:25                               :::*                  
[root@localhost ~]# systemctl status  mariadb.service #查看运行状态
● mariadb.service - MariaDB database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
   Active: active (running) since Mon 2021-08-23 07:56:39 PDT; 26s ago
  Process: 104401 ExecStartPost=/usr/libexec/mariadb-wait-ready $MAINPID (code=exited, status=0/SUCCESS)
  Process: 104318 ExecStartPre=/usr/libexec/mariadb-prepare-db-dir %n (code=exited, status=0/SUCCESS)
 Main PID: 104400 (mysqld_safe)
    Tasks: 20
   CGroup: /system.slice/mariadb.service
           ├─104400 /bin/sh /usr/bin/mysqld_safe --basedir=/usr
           └─104565 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/u...

Aug 23 07:56:37 localhost.localdomain mariadb-prepare-db-dir[104318]: MySQL manual for more ins...
Aug 23 07:56:37 localhost.localdomain mariadb-prepare-db-dir[104318]: Please report any problem...
Aug 23 07:56:37 localhost.localdomain mariadb-prepare-db-dir[104318]: The latest information ab...
Aug 23 07:56:37 localhost.localdomain mariadb-prepare-db-dir[104318]: You can find additional i...
Aug 23 07:56:37 localhost.localdomain mariadb-prepare-db-dir[104318]: http://dev.mysql.com
Aug 23 07:56:37 localhost.localdomain mariadb-prepare-db-dir[104318]: Consider joining MariaDB'...
Aug 23 07:56:37 localhost.localdomain mariadb-prepare-db-dir[104318]: https://mariadb.org/get-i...
Aug 23 07:56:37 localhost.localdomain mysqld_safe[104400]: 210823 07:56:37 mysqld_safe Logging....
Aug 23 07:56:37 localhost.localdomain mysqld_safe[104400]: 210823 07:56:37 mysqld_safe Startin...l
Aug 23 07:56:39 localhost.localdomain systemd[1]: Started MariaDB database server.
Hint: Some lines were ellipsized, use -l to show in full.

[root@localhost ~]# mysql -uroot -p #进入mysql
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 5.5.68-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 databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
4 rows in set (0.00 sec)
列出库
MariaDB [(none)]> set password = password('123456');
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> exit
Bye
[root@localhost ~]# mysql -uroot -p123456
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 7
Server version: 5.5.68-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)]> exit
Bye
[root@localhost ~]# mysql -uroot -p123
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
设置密码

2.2 mysql的程序组成

客户端与服务的程序

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

mysql工具使用

语法:mysql [OPTIONS] [database]
常用的OPTIONS-uUSERNAME      //指定用户名,默认为root
    -hHOST          //指定服务器主机,默认为localhost,推荐使用ip地址
    -pPASSWORD      //指定用户的密码
    -P#             //指定数据库监听的端口,这里的#需用实际的端口号代替,如-P3306
    -V              //查看当前使用的mysql版本
    -e              //不登录mysql执行sql语句后退出,常用于脚本
    -S              //指定套接字的路径
[root@localhost ~]# mysql -V
mysql  Ver 15.1 Distrib 5.5.68-MariaDB, for Linux (x86_64) using readline 5.1
[root@localhost ~]# mysql -uroot -p123456 -h127.0.0.1
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 10
Server version: 5.5.68-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)]> 

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

2.3 服务器监听的两种socket地址

socket类型说明
ip socket默认监听在tcp的3306端口,支持远程通信
unix sock监听在sock文件上(/tmp/mysql.sock,/var/lib/mysql /mysql.sock)
命令效果
show(展示)databases; #查看数据库
use 库名#切换库
show tables#在库中查看表
describe 表名#查看表的结构
create(创建) database (if not exists//严谨加上) (库名);//创建数据库
drop (删除) database 库名;#删除库

##DDL操作

3. 基础操作

3.1 库ddl操作

MariaDB [(none)]> create database lhj; #创建数据库
Query OK, 1 row affected (0.01 sec)


MariaDB [(none)]> show databases; 列出
+--------------------+
| Database           |
+--------------------+
| information_schema |
| lhj                |
| mysql              |
| performance_schema |
| test               |
+--------------------+
5 rows in set (0.00 sec)

MariaDB [(none)]> use lhj; #进入数据库
Database changed


MariaDB [lhj]> CREATE TABLE lhjtable (id int NOT NULL,name VARCHAR(100) NOT NULL,age tinyint) # 创建表
    -> ;
Query OK, 0 rows affected (0.00 sec)

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

MariaDB [(none)]> create database jjj;
ERROR 1007 (HY000): Can't create database 'jjj'; database exists
MariaDB [(none)]> create database if not exists jjj; #不存在就创建,存在就不创建
Query OK, 1 row affected, 1 warning (0.00 sec)

MariaDB [(none)]> drop database if exists jjj; #删除数据库
Query OK, 0 rows affected (0.01 sec)

3.2 表ddl操作

MariaDB [lhj]> create table abc (id int not null,name varchar(100) not null,age tinyint);
Query OK, 0 rows affected (0.00 sec)

M
MariaDB [lhj]> drop table abc;
Query OK, 0 rows affected (0.00 sec)

3.3 用户操作

用户操作

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

这里(‘USERNAME’@‘HOST’)的HOST用于限制此用户可通过哪些主机远程连接mysql程序,其值可为:
IP地址,如:192.168.10.1
通配符
%:匹配任意长度的任意字符,常用于设置允许从任何主机登录
_:匹配任意单个字符

MariaDB [(none)]> create user admin@localhost identified by '123456';
Query OK, 0 rows affected (0.00 sec)

[root@localhost ~]# mysql -uadmin -p123456 -hlocalhost
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 4
Server version: 5.5.68-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)]> drop user admin@localhost;
Query OK, 0 rows affected (0.01 sec)

#需要进入root用户才能删除用户

3.4 查看show

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 |
| latin2   | ISO 8859-2 Central European | latin2_general_ci   |      1 |
| swe7     | 7bit Swedish                | swe7_swedish_ci     |      1 |
| ascii    | US ASCII                    | ascii_general_ci    |      1 |
| ujis     | EUC-JP Japanese             | ujis_japanese_ci    |      3 |
| sjis     | Shift-JIS Japanese          | sjis_japanese_ci    |      2 |
| hebrew   | ISO 8859-8 Hebrew           | hebrew_general_ci   |      1 |
| tis620   | TIS620 Thai                 | tis620_thai_ci      |      1 |
| euckr    | EUC-KR Korean               | euckr_korean_ci     |      2 |
| koi8u    | KOI8-U Ukrainian            | koi8u_general_ci    |      1 |
| gb2312   | GB2312 Simplified Chinese   | gb2312_chinese_ci   |      2 |
| greek    | ISO 8859-7 Greek            | greek_general_ci    |      1 |
| cp1250   | Windows Central European    | cp1250_general_ci   |      1 |
| gbk      | GBK Simplified Chinese      | gbk_chinese_ci      |      2 |
| latin5   | ISO 8859-9 Turkish          | latin5_turkish_ci   |      1 |
| armscii8 | ARMSCII-8 Armenian          | armscii8_general_ci |      1 |
| utf8     | UTF-8 Unicode               | utf8_general_ci     |      3 |
| ucs2     | UCS-2 Unicode               | ucs2_general_ci     |      2 |
| cp866    | DOS Russian                 | cp866_general_ci    |      1 |
| keybcs2  | DOS Kamenicky Czech-Slovak  | keybcs2_general_ci  |      1 |
| macce    | Mac Central European        | macce_general_ci    |      1 |
| macroman | Mac West European           | macroman_general_ci |      1 |
| cp852    | DOS Central European        | cp852_general_ci    |      1 |
| latin7   | ISO 8859-13 Baltic          | latin7_general_ci   |      1 |
| utf8mb4  | UTF-8 Unicode               | utf8mb4_general_ci  |      4 |
| cp1251   | Windows Cyrillic            | cp1251_general_ci   |      1 |
| utf16    | UTF-16 Unicode              | utf16_general_ci    |      4 |
| cp1256   | Windows Arabic              | cp1256_general_ci   |      1 |
| cp1257   | Windows Baltic              | cp1257_general_ci   |      1 |
| utf32    | UTF-32 Unicode              | utf32_general_ci    |      4 |
| binary   | Binary pseudo charset       | binary              |      1 |
| geostd8  | GEOSTD8 Georgian            | geostd8_general_ci  |      1 |
| cp932    | SJIS for Windows Japanese   | cp932_japanese_ci   |      2 |
| eucjpms  | UJIS for Windows Japanese   | eucjpms_japanese_ci |      3 |
+----------+-----------------------------+---------------------+--------+
39 rows in set (0.00 sec)
#查看支持字符集
MariaDB [lhj]> show engines;
+--------------------+---------+----------------------------------------------------------------------------------+--------------+------+------------+
| Engine             | Support | Comment                                                                          | Transactions | XA   | Savepoints |
+--------------------+---------+----------------------------------------------------------------------------------+--------------+------+------------+
| InnoDB             | DEFAULT | Percona-XtraDB, Supports transactions, row-level locking, and foreign keys       | YES          | YES  | YES        |
| MRG_MYISAM         | YES     | Collection of identical MyISAM tables                                            | NO           | NO   | NO         |
| MyISAM             | YES     | Non-transactional engine with good performance and small data footprint          | NO           | NO   | NO         |
| BLACKHOLE          | YES     | /dev/null storage engine (anything you write to it disappears)                   | NO           | NO   | NO         |
| PERFORMANCE_SCHEMA | YES     | Performance Schema                                                               | NO           | NO   | NO         |
| CSV                | YES     | Stores tables as CSV files                                                       | NO           | NO   | NO         |
| ARCHIVE            | YES     | gzip-compresses tables for a low storage footprint                               | NO           | NO   | NO         |
| MEMORY             | YES     | Hash based, stored in memory, useful for temporary tables                        | NO           | NO   | NO         |
| FEDERATED          | YES     | Allows to access tables on other MariaDB servers, supports transactions and more | YES          | NO   | YES        |
| Aria               | YES     | Crash-safe tables with MyISAM heritage                                           | NO           | NO   | NO         |
+--------------------+---------+----------------------------------------------------------------------------------+--------------+------+------------+
10 rows in set (0.00 sec)
#查看支持的储存引擎
MariaDB [lhj]> show create table lhjtable;
+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                                                              |
+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| lhjtable | CREATE TABLE `lhjtable` (
  `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)
#查看表的创建方式
MariaDB [mysql]> show tables from lhj;
+---------------+
| Tables_in_lhj |
+---------------+
| lhjtable      |
+---------------+
1 row in set (0.00 sec)
#不进入库查看表
MariaDB [mysql]> desc lhj.lhjtable;
+-------+--------------+------+-----+---------+-------+
| 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.02 sec)
#查看lhj库中lhjtable表的结构
MariaDB [mysql]> show table status like 'user' \G
*************************** 1. row ***************************
           Name: user
         Engine: MyISAM
        Version: 10
     Row_format: Dynamic
           Rows: 6
 Avg_row_length: 63
    Data_length: 476
Max_data_length: 281474976710655
   Index_length: 2048
      Data_free: 96
 Auto_increment: NULL
    Create_time: 2021-08-23 07:56:37
    Update_time: 2021-08-23 19:24:06
     Check_time: 2021-08-23 18:54:03
      Collation: utf8_bin
       Checksum: NULL
 Create_options: 
        Comment: Users and global privileges
1 row in set (0.00 sec)
#查看表的状态

3.5 帮助文档

MariaDB [mysql]> 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
    [(create_definition,...)]
    [table_options]
    [partition_options]
    select_statement
#查看创建表的帮助文档

3.6 ALTER数据库修改操作

MariaDB [(none)]> alter database lhj character set utf8;
Query OK, 1 row affected (0.01 sec)
#修改数据库字符集为utf8

MariaDB [lhj]> alter table zuoye add tel int(11);
Query OK, 10 rows affected (0.02 sec)              
Records: 10  Duplicates: 0  Warnings: 0

MariaDB [lhj]> desc zuoye;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(100) | NO   |     | NULL    |                |
| age   | tinyint(4)   | YES  |     | NULL    |                |
| tel   | int(11)      | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
//将表添加新的一列
MariaDB [lhj]> alter table zuoye change tel phone varchar(12);
Query OK, 10 rows affected (0.01 sec)              
Records: 10  Duplicates: 0  Warnings: 0

MariaDB [lhj]> desc zuoye;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(100) | NO   |     | NULL    |                |
| age   | tinyint(4)   | YES  |     | NULL    |                |
| phone | varchar(12)  | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
///将tel变为phone 且类型为varchar
MariaDB [lhj]> alter table zuoye rename jingri;
Query OK, 0 rows affected (0.00 sec)

MariaDB [lhj]> show tables;
+---------------+
| Tables_in_lhj |
+---------------+
| jingri        |
| lhjtable      |
+---------------+
2 rows in set (0.00 sec)
///修改表名

4.DML操作

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

4.1 INSERT语句

先创建一个表

MariaDB [lhj]> create table zaoye(id int not null auto_increment,name varchar(100) not null,age tinyint(4),PRIMARY KEY(id));
Query OK, 0 rows affected (0.00 sec)

MariaDB [lhj]> desc zaoye;
+-------+--------------+------+-----+---------+----------------+
| 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.01 sec)

MariaDB [lhj]> select * from zaoye; # 表里数据为空 
Empty set (0.01 sec)

插入一条数据

MariaDB [lhj]> insert into zaoye (id,name,age) value(8,'chenshuo',10);
Query OK, 1 row affected (0.00 sec)

插入多条

MariaDB [lhj]> insert into zaoye (id,name,age) values(1,'tom',20),(2,'jerry',23),(3,'wangqing',25),(4,'sean',28),(5,'zhangshan',26),(6,'zhangshan',20),(7,'lisi',NULL);
Query OK, 7 rows affected (0.00 sec)
Records: 7  Duplicates: 0  Warnings: 0

4.2 select 查询语句

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

条件判断语句where

操作类型常用操作符
操作符>,<,>=,<=,=,!=\between…and…\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 [lhj]> select name from jingri;
+-----------+
| name      |
+-----------+
| tom       |
| jerry     |
| sean      |
| zhangshan |
| lisi      |
| wangwu    |
+-----------+
6 rows in set (0.00 sec)
///查找name列
MariaDB [lhj]> select *  from jingri order by age;
+----+-----------+------+-------+
| id | name      | age  | phone |
+----+-----------+------+-------+
|  1 | tom       |   20 | NULL  |
|  2 | jerry     |   23 | NULL  |
|  5 | zhangshan |   26 | NULL  |
|  4 | sean      |   28 | NULL  |
|  7 | lisi      |   50 | NULL  |
|  9 | wangwu    |  100 | NULL  |
+----+-----------+------+-------+
6 rows in set (0.00 sec)
\\\以age升序排列
MariaDB [lhj]> select *  from jingri order by age desc;
+----+-----------+------+-------+
| id | name      | age  | phone |
+----+-----------+------+-------+
|  9 | wangwu    |  100 | NULL  |
|  7 | lisi      |   50 | NULL  |
|  4 | sean      |   28 | NULL  |
|  5 | zhangshan |   26 | NULL  |
|  2 | jerry     |   23 | NULL  |
|  1 | tom       |   20 | NULL  |
+----+-----------+------+-------+
6 rows in set (0.00 sec)
 以age降序
MariaDB [lhj]> select * from jingri where age >= 30;
+----+--------+------+-------+
| id | name   | age  | phone |
+----+--------+------+-------+
|  7 | lisi   |   50 | NULL  |
|  9 | wangwu |  100 | NULL  |
+----+--------+------+-------+
2 rows in set (0.00 sec)
找出age大于等于30的人
MariaDB [lhj]> select * from jingri where age between 25 and 35;
+----+-----------+------+-------+
| id | name      | age  | phone |
+----+-----------+------+-------+
|  4 | sean      |   28 | NULL  |
|  5 | zhangshan |   26 | NULL  |
+----+-----------+------+-------+
2 rows in set (0.00 sec)
找出age在25-35的人

4.3 update 语句

意为更新,修改表内容

MariaDB [lhj]> update jingri set age = 99 where name ='lisi';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [lhj]> select * from jingri where name ='lisi';
+----+------+------+-------+
| id | name | age  | phone |
+----+------+------+-------+
|  7 | lisi |   99 | NULL  |
+----+------+------+-------+
1 row in set (0.00 sec)
修改lisiage为99
MariaDB [lhj]> delete from jingri order by age limit 1;
Query OK, 1 row affected (0.00 sec)

MariaDB [lhj]> select * from jingri ;
+----+-----------+------+-------+
| id | name      | age  | phone |
+----+-----------+------+-------+
|  2 | jerry     |   23 | NULL  |
|  4 | sean      |   28 | NULL  |
|  5 | zhangshan |   26 | NULL  |
|  7 | lisi      |   99 | NULL  |
|  9 | wangwu    |  100 | NULL  |
+----+-----------+------+-------+
5 rows in set (0.00 sec)
删除年龄最小的一个

4.4 truncate语句

删除表

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

DCL权限操作

5.1 权限类型(priv_type)

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

指定要操作的对象db_name.table_name

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

WITH GRANT OPTION:被授权的用户可将自己的权限副本转赠给其他用户,也就是权限复制。

先创建一个用户

MariaDB [lhj]> create user '123'@'localhost' identified by '1';
Query OK, 0 rows affected (0.00 sec)

MariaDB [lhj]> grant all on *.* to '123'@'localhost' identified by '1';
Query OK, 0 rows affected (0.00 sec)

MariaDB [lhj]> flush privileges;
Query OK, 0 rows affected (0.00 sec)
授权123在本机上访问所有数据库的权限  ///localhost 也可表示为127.0.0.1
MariaDB [lhj]> grant all on lhj.* to '123'@'192.168.216.182' identified by '1';
Query OK, 0 rows affected (0.00 sec)

MariaDB [lhj]> flush privileges;
Query OK, 0 rows affected (0.00 sec)
权123在192.168.216.182上访问lhj数据库的权限 
MariaDB [lhj]> grant all on lhj.* to '123'@'%' identified by '1';
Query OK, 0 rows affected (0.00 sec)

MariaDB [lhj]> flush privileges;
Query OK, 0 rows affected (0.00 sec)
123可在所有地方访问lhj数据库

5.2 查看授权

MariaDB [lhj]> show grants;
+----------------------------------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost                                                                                                              |
+----------------------------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9' WITH GRANT OPTION |
| GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION                                                                           |
+----------------------------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)
查看当前用户权限
MariaDB [lhj]> show grants for '123'@'192.168.216.182';
+------------------------------------------------------------------------------------------------------------------+
| Grants for 123@192.168.216.182                                                                                   |
+------------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO '123'@'192.168.216.182' IDENTIFIED BY PASSWORD '*E6CC90B878B948C35E92B003C792C46C58C4AF40' |
| GRANT ALL PRIVILEGES ON `lhj`.* TO '123'@'192.168.216.182'                                                       |
+------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)
查看指定用户授权信息

5.3 取消授权

MariaDB [lhj]> revoke all on lhj.* from '123'@'192.168.216.182';
Query OK, 0 rows affected (0.00 sec)

MariaDB [lhj]> flush privileges;
Query OK, 0 rows affected (0.00 sec)

MariaDB [lhj]> show grants for '123'@'192.168.216.182';
+------------------------------------------------------------------------------------------------------------------+
| Grants for 123@192.168.216.182                                                                                   |
+------------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO '123'@'192.168.216.182' IDENTIFIED BY PASSWORD '*E6CC90B878B948C35E92B003C792C46C58C4AF40' |
+------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
  • mysql服务进程启动时会读取mysql库中的所有授权表至内存中:

  • GRANT或REVOKE等执行权限操作会保存于表中,mysql的服务进程会自动重读授权表,并更新至内存中

  • 对于不能够或不能及时重读授权表的命令,可手动让mysql的服务进程重读授权表

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值