MySQL数据库基础进阶

关系型数据库介绍

数据结构模型

数据结构模型主要有:

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

关系模型:
二维关系: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安装

mysql安装方式有三种:

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

配置mysql的yum源

[root@localhost ~]# wget http://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm

位置:https://repo.mysql.com//mysql57-community-release-el7-11.noarch.rpm [跟随至新的 URL]
--2022-07-22 05:48:05--  https://repo.mysql.com//mysql57-community-release-el7-11.noarch.rpm
正在解析主机 repo.mysql.com (repo.mysql.com)... 23.55.248.248
正在连接 repo.mysql.com (repo.mysql.com)|23.55.248.248|:443... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:25680 (25K) [application/x-redhat-package-manager]
正在保存至: “mysql57-community-release-el7-11.noarch.rpm”

mysql57-community-release-el7-11.noarch.rpm    100%[=================================================================================================>]  25.08K  83.1KB/s  用时 0.3s

2022-07-22 05:48:07 (83.1 KB/s) - 已保存 “mysql57-community-release-el7-11.noarch.rpm” [25680/25680])

[root@localhost ~]#

[root@localhost ~]# rpm -Uvh mysql57-community-release-el7-11.noarch.rpm
警告:mysql57-community-release-el7-11.noarch.rpm: 头V3 DSA/SHA1 Signature, 密钥 ID 5072e1f5: NOKEY
Verifying...                          ################################# [100%]
准备中...                          ################################# [100%]
正在升级/安装...
   1:mysql57-community-release-el7-11 ################################# [100%]

使用yum安装mysql5.7,关闭此模块yum module disable mysql

[root@localhost ~]# yum module disable mysql
上次元数据过期检查:0:13:35 前,执行于 2022年07月22日 星期五 06时04分16秒。
依赖关系解决。
=========================================================================================================================================================================================
 软件包                                      架构                                       版本                                           仓库                                         大小
=========================================================================================================================================================================================
禁用模块:
 mysql

事务概要
=========================================================================================================================================================================================

确定吗?[y/N]: y
完毕!
[root@localhost ~]# yum -y install mysql-community-server mysql-community-client mysql-community-common mysql-community-devel --nogpgcheck
....

已安装:
  mysql-community-client-5.7.38-1.el7.x86_64    mysql-community-common-5.7.38-1.el7.x86_64       mysql-community-devel-5.7.38-1.el7.x86_64    mysql-community-libs-5.7.38-1.el7.x86_64
  mysql-community-server-5.7.38-1.el7.x86_64    ncurses-compat-libs-6.1-9.20180224.el8.x86_64

完毕!
[root@localhost ~]#

mysql配置

启动服务并设置开机自启

[root@localhost ~]# systemctl enable --now 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 Fri 2022-07-22 06:22:19 EDT; 2s ago
     Docs: man:mysqld(8)
           http://dev.mysql.com/doc/refman/en/using-systemd.html
  Process: 3856 ExecStart=/usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid $MYSQLD_OPTS (code=exited, status=0/SUCCESS)
  Process: 3802 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
 Main PID: 3858 (mysqld)
    Tasks: 27 (limit: 23330)
   Memory: 328.2M
   CGroup: /system.slice/mysqld.service
           └─3858 /usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid

7月 22 06:22:15 localhost.localdomain systemd[1]: Starting MySQL Server...
7月 22 06:22:19 localhost.localdomain systemd[1]: Started MySQL Server.
[root@localhost ~]#

查看端口

[root@localhost ~]# ss -antlp
State          Recv-Q         Send-Q                  Local Address:Port                   Peer Address:Port         Process
LISTEN         0              128                         127.0.0.1:6010                        0.0.0.0:*             users:(("sshd",pid=2427,fd=15))
LISTEN         0              128                           0.0.0.0:111                         0.0.0.0:*             users:(("rpcbind",pid=1016,fd=4),("systemd",pid=1,fd=116))
LISTEN         0              32                      192.168.122.1:53                          0.0.0.0:*             users:(("dnsmasq",pid=2125,fd=6))
LISTEN         0              128                           0.0.0.0:22                          0.0.0.0:*             users:(("sshd",pid=1279,fd=5))
LISTEN         0              5                           127.0.0.1:631                         0.0.0.0:*             users:(("cupsd",pid=1285,fd=10))
LISTEN         0              128                             [::1]:6010                           [::]:*             users:(("sshd",pid=2427,fd=14))
LISTEN         0              80                                  *:3306                              *:*             users:(("mysqld",pid=3858,fd=22))
LISTEN         0              128                              [::]:111                            [::]:*             users:(("rpcbind",pid=1016,fd=6),("systemd",pid=1,fd=118))
LISTEN         0              128                              [::]:22                             [::]:*             users:(("sshd",pid=1279,fd=7))
LISTEN         0              5                               [::1]:631                            [::]:*             users:(("cupsd",pid=1285,fd=9))
[root@localhost ~]#

查看密码

[root@localhost ~]# grep "password" /var/log/mysqld.log
2022-07-22T10:22:17.900718Z 1 [Note] A temporary password is generated for root@localhost: bf.Zx4-qShsi

登录并修改密码

[root@localhost ~]# mysql -uroot -pbf.Zx4-qShsi
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.38

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

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> 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.00 sec)

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

mysql> exit
Bye
[root@localhost ~]#

mysql的程序组成

  • 客户端

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

    • mysqld

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 -phaha123! -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                |
| hahha        |
+--------------------+

服务器监听的两种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中定义数据字段的类型对数据库的优化是非常重要的。MySQL支持多种类型,大致可以分为三类:数值、日期/时间和字符串(字符)类型。

数值类型
MySQL支持所有标准SQL数值数据类型。这些类型包括严格数值数据类型(INTEGER、SMALLINT、DECIMAL和NUMERIC),以及近似数值数据类型(FLOAT、REAL和DOUBLE PRECISION)。

关键字INT是INTEGER的同义词,关键字DEC是DECIMAL的同义词。BIT数据类型保存位字段值,并且支持MyISAM、MEMORY、InnoDB和BDB表。作为SQL标准的扩展,MySQL也支持整数类型TINYINT、MEDIUMINT和BIGINT。
下面的表显示了需要的每个整数类型的存储和范围
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

注意: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 类型,可存储的最大长度不同,可根据实际情况选择。

mysql数据库操作

DDL操作

数据库操作

创建数据库

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

查看当前实例有哪些数据库

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| haha        |
+--------------------+
5 rows in set (0.00 sec)

删除数据库
语法:DROP DATABASE [IF EXISTS] ‘DB_NAME’;
删除数据库haha

mysql> DROP DATABASE IF EXISTS haha;
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)
表操作

创建表
语法:CREATE TABLE table_name (col1 datatype 修饰符,col2 datatype 修饰符) ENGINE=‘存储引擎类型’;
在数据库haha里创建表haha

mysql> CREATE DATABASE haha;      //创建数据库haha
Query OK, 1 row affected (0.00 sec)

mysql> use haha;      //进入haha数据库
Database changed
mysql> CREATE TABLE haha (id int NOT NULL,name VARCHAR(100) NOT NULL,age tinyint);      //创建haha表
Query OK, 0 rows affected (0.09 sec)

查看当前数据库有哪些表

mysql> SHOW TABLES;
+----------------------+
| Tables_in_wangqingge |
+----------------------+
| haha                 |
+----------------------+
1 row in set (0.00 sec)

删除表
语法:DROP TABLE [ IF EXISTS ] ‘table_name’;
删除表haha

mysql> DROP TABLE haha;
Query OK, 0 rows affected (0.01 sec)

mysql> SHOW TABLES;
Empty set (0.00 sec)
用户操作

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

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

  • IP地址,如:172.16.12.129
  • 通配符
    • %:匹配任意长度的任意字符,常用于设置允许从任何主机登录
    • _:匹配任意单个字符

数据库用户创建

语法:CREATE USER 'username'@'host' [IDENTIFIED BY 'password'];
创建数据库用户hehe

mysql> CREATE USER 'hehe'@'127.0.0.1' IDENTIFIED BY 'hehe123!';
Query OK, 0 rows affected (0.00 sec)

使用新创建的用户和密码登录

[root@localhost ~]# mysql -uhehe -phehe123! -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 'hehe'@'127.0.0.1';
Query OK, 0 rows affected (0.00 sec)
查看命令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                |
| hehe               |
+--------------------+
5 rows in set (0.00 sec)
mysql> SHOW TABLES FROM hehe;         //不进入某数据库而列出其包含的所有表
+----------------------+
| Tables_in_wangqingge |
+----------------------+
| hehe                 |
+----------------------+
1 row in set (0.00 sec)

查看表结构

语法:DESC [db_name.]table_name;
mysql> DESC hehe.haha;   //数据库名.表名
+-------+--------------+------+-----+---------+-------+
| 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 hehe.haha;
+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                                                              |
+----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| wangqing | CREATE TABLE `haha` (
  `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 hehe;      //进入数据库hehe
Database changed
mysql> SHOW TABLE STATUS LIKE 'haha'\G      //查看haha表的状态
*************************** 1. row ***************************
           Name: haha
         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 18:53:21
    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;       //获取创建表的帮助
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
 ......
 ......

DML操作

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

INSERT语句

DML操作之增操作insert

语法:INSERT [INTO] table_name [(column_name,...)] {VALUES | VALUE} (value1,...),(...),...

mysql> usehehe;
Database changed
mysql> INSERT INTO haha (id,name,age) VALUE (1,'tom',20);       //一次插入一条记录
Query OK, 1 row affected (0.01 sec)


mysql> INSERT INTO haha (id,name,age) VALUES (2,'jerry',23),(3,'hgaf',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
SELECT语句

字段column表示法

表示符代表什么?
*所有字段
as字段别名,如col1 AS alias1
当表名很长时用别名代替

条件判断语句WHERE

操作类型常用操作符
操作符>,<,>=,<=,=,!=
BETWEEN column# AND column#
LIKE:模糊匹配
RLIKE:基于正则表达式进行模式匹配
IS NOT NULL:非空
IS NULL:空
条件逻辑操作AND
OR
NOT

ORDER BY:排序,默认为升序(ASC)

ORDER BY语句意义
ORDER BY ‘column_name’根据column_name进行升序排序
ORDER BY ‘column_name’ DESC根据column_name进行降序排序
ORDER BY ’column_name’ LIMIT 2根据column_name进行升序排序并只取前2个结果
ORDER BY ‘column_name’ LIMIT 1,2根据column_name进行升序排序
并且略过第1个结果取后面的2个结果

DML操作之查操作select

语法:SELECT column1,column2,... FROM table_name [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];

mysql> use hehe;
Database changed
mysql> select * from haha;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | tom       |   20 |
|  2 | jerry     |   23 |
|  3 | jdddb     |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
|  7 | lisi      | NULL |
+----+-----------+------+
7 rows in set (0.00 sec)

mysql> SELECT name FROM haha;
+-----------+
| name      |
+-----------+
| tom       |
| jerry     |
| jdddb     |
| sean      |
| zhangshan |
| zhangshan |
| lisi      |
+-----------+
7 rows in set (0.01 sec)

mysql> SELECT * FROM haha ORDER BY age;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  7 | lisi      | NULL |
|  1 | tom       |   20 |
|  6 | zhangshan |   20 |
|  2 | jerry     |   23 |
|  3 | jdddb     |   25 |
|  5 | zhangshan |   26 |
|  4 | sean      |   28 |
+----+-----------+------+
7 rows in set (0.00 sec)

mysql> SELECT * FROM haha ORDER BY age DESC;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  3 | jdddb     |   25 |
|  2 | jerry     |   23 |
|  1 | tom       |   20 |
|  6 | zhangshan |   20 |
|  7 | lisi      | NULL |
+----+-----------+------+
7 rows in set (0.00 sec)

mysql> SELECT * FROM haha ORDER BY age limit 2;
+----+------+------+
| id | name | age  |
+----+------+------+
|  7 | lisi | NULL |
|  1 | tom  |   20 |
+----+------+------+
2 rows in set (0.00 sec)

mysql> SELECT * FROM haha 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 haha WHERE age >= 25;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  3 | jdddb     |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
+----+-----------+------+
3 rows in set (0.00 sec)

mysql> SELECT * FROM haha WHERE age >= 25 AND name = 'zhangshan';
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  5 | zhangshan |   26 |
+----+-----------+------+
1 row in set (0.00 sec)

mysql> SELECT * FROM haha WHERE age BETWEEN 23 and 28;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  2 | jerry     |   23 |
|  3 | jdddb     |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
+----+-----------+------+
4 rows in set (0.00 sec)

mysql> select * from haha where age is not null;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | tom       |   20 |
|  2 | jerry     |   23 |
|  3 | jdddb     |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
+----+-----------+------+
6 rows in set (0.00 sec)

mysql> select * from haha where age is null;
+----+------+------+
| id | name | age  |
+----+------+------+
|  7 | lisi | NULL |
+----+------+------+
1 row in set (0.00 sec)
date语句

DML操作之改操作update

语法:UPDATE table_name SET column1 = new_value1[,column2 = new_value2,...] [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];

mysql> select * from haha;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | tom       |   20 |
|  2 | jerry     |   23 |
|  3 | jfadd     |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
|  7 | lisi      | NULL |
+----+-----------+------+
7 rows in set (0.00 sec)

mysql> update haha set age = 30 where name = 'lisi';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from haha where name = 'lisi';
+----+------+------+
| id | name | age  |
+----+------+------+
|  7 | lisi |   30 |
+----+------+------+
1 row in set (0.00 sec)
delete语句

DML操作之删操作delete

语法:DELETE FROM table_name [WHERE clause] [ORDER BY 'column_name' [DESC]] [LIMIT [m,]n];

mysql> select * from haha;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | tom       |   20 |
|  2 | jerry     |   23 |
|  3 | jcdd      |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
|  7 | lisi      |   30 |
+----+-----------+------+
7 rows in set (0.00 sec)

mysql> delete from haha where id = 7;       //删除某条记录
Query OK, 1 row affected (0.00 sec)

mysql> select * from haha;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | tom       |   20 |
|  2 | jerry     |   23 |
|  3 | jahdd     |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
+----+-----------+------+
6 rows in set (0.00 sec)


mysql> delete from haha;        //删除整张表的内容
Query OK, 6 rows affected (0.00 sec)

mysql> select * from haha;
Empty set (0.00 sec)

mysql> desc haha;
+-------+--------------+------+-----+---------+-------+
| 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)
truncate语句

truncate与delete的区别:

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

mysql> select * from haha;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | tom       |   20 |
|  2 | jerry     |   23 |
|  3 | jdddb   |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
|  7 | lisi      | NULL |
+----+-----------+------+
7 rows in set (0.00 sec)

mysql> truncate haha;
Query OK, 0 rows affected (0.01 sec)

mysql> select * from haha;
Empty set (0.00 sec)

mysql> desc haha;
+-------+--------------+------+-----+---------+-------+
| 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)

DCL操作

创建授权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                |
| hehe             |
+--------------------+
5 rows in set (0.00 sec)

授权haha用户在数据库本机上登录访问所有数据库

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

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

授权haha用户在192.168.40.99上远程登录访问hehe数据库

mysql> GRANT ALL ON hehe.* TO 'haha'@'192.168.40.99' IDENTIFIED BY 'haha123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)

授权haha用户在所有位置上远程登录访问hehe数据库

mysql> GRANT ALL ON *.* TO 'haha'@'%' IDENTIFIED BY 'haha123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)
查看授权

查看当前登录用户的授权信息

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)

查看指定用户haha的授权信息

mysql> SHOW GRANTS FOR haha;
+-----------------------------------------------+
| Grants for haha@%                         |
+-----------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'haha'@'%' |
+-----------------------------------------------+
1 row in set (0.00 sec)

mysql> SHOW GRANTS FOR 'haha'@'localhost';
+-------------------------------------------------------+
| Grants for haha@localhost                         |
+-------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'haha'@'localhost' |
+-------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SHOW GRANTS FOR 'haha'@'127.0.0.1';
+-------------------------------------------------------+
| Grants for haha@127.0.0.1                         |
+-------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'haha'@'127.0.0.1' |
+-------------------------------------------------------+
1 row in set (0.00 sec)
取消授权REVOKE
语法:REVOKE priv_type,... ON db_name.table_name FROM 'username'@'host';

mysql> REVOKE ALL ON *.* FROM 'haha'@'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的服务进程重读授权表
mysql> FLUSH PRIVILEGES;

实战案例

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

mysql> create database haha;
Query OK, 1 row affected (0.00 sec)
mysql> use haha;
Database changed
mysql> create table student(id int(11) not null  primary key auto_increment,name varchar(100) not null,age tinyint(4));
Query OK, 0 rows affected (0.00 sec)

mysql> desc student;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(100) | NO   |     | NULL    |                |
| age   | tinyint(4)   | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
3 rows in set (0.03 sec)
mysql>

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

mysql> select * from student;
Empty set (0.00 sec)

mysql> 

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

mysql> insert student (id,name,age) values (1,'tom',20),(2,'jerry',23),(3,'haha',20),(4,'sean',28),(5,'zhangsan',26),(6,'zhangsan',20),(7,'lisi',NULL),(8,'chenshuo',10),(9,'wangwu',3),(10,'qiuyi',15),(11,'qiuxiaotian',20);
Query OK, 11 rows affected (0.00 sec)
Records: 11  Duplicates: 0  Warnings: 0

mysql> select * from student;
+----+-------------+------+
| id | name        | age  |
+----+-------------+------+
|  1 | tom         |   20 |
|  2 | jerry       |   23 |
|  3 | haha        |   20 |
|  4 | sean        |   28 |
|  5 | zhangsan    |   26 |
|  6 | zhangsan    |   20 |
|  7 | lisi        | NULL |
|  8 | chenshuo    |   10 |
|  9 | wangwu      |    3 |
| 10 | qiuyi       |   15 |
| 11 | qiuxiaotian |   20 |
+----+-------------+------+
11 rows in set (0.00 sec)

mysql>

5.修改lisi的年龄为50

mysql> update student set age = 50 where name='lisi';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0
mysql> select * from student where name='lisi';
+----+------+------+
| id | name | age  |
+----+------+------+
|  7 | lisi |   50 |
+----+------+------+
1 row in set (0.00 sec)

mysql>

6.以age字段降序排序

mysql> select * from student order by age desc;
+----+-------------+------+
| id | name        | age  |
+----+-------------+------+
|  7 | lisi        |   50 |
|  4 | sean        |   28 |
|  5 | zhangsan    |   26 |
|  2 | jerry       |   23 |
|  1 | tom         |   20 |
|  3 | haha        |   20 |
|  6 | zhangsan    |   20 |
| 11 | qiuxiaotian |   20 |
| 10 | qiuyi       |   15 |
|  8 | chenshuo    |   10 |
|  9 | wangwu      |    3 |
+----+-------------+------+
11 rows in set (0.00 sec)

mysql>

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

mysql> select * from student order by age limit 2,1;
+----+-------------+------+
| id | name        | age  |
+----+-------------+------+
| 10 | qiuyi       |   15 |
+----+-------------+------+
1 rows in set (0.00 sec)

mysql>

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

mysql> select * from student order by age desc limit 4;
+----+----------+------+
| id | name     | age  |
+----+----------+------+
|  7 | lisi     |   50 |
|  4 | sean     |   28 |
|  5 | zhangsan |   26 |
|  2 | jerry    |   23 |
+----+----------+------+
4 rows in set (0.00 sec)

mysql>

9.查询student表中名字叫zhangsan的记录

mysql> select * from student where name='zhangsan';
+----+----------+------+
| id | name     | age  |
+----+----------+------+
|  5 | zhangsan |   26 |
|  6 | zhangsan |   20 |
+----+----------+------+
2 rows in set (0.00 sec)

mysql>

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

mysql> select * from student where name='zhangsan' and age > 20;
+----+----------+------+
| id | name     | age  |
+----+----------+------+
|  5 | zhangsan |   26 |
+----+----------+------+
1 row in set (0.00 sec)

mysql>

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

mysql> select * from student where age BETWEEN 20 and 30;
+----+-------------+------+
| id | name        | age  |
+----+-------------+------+
|  1 | tom         |   20 |
|  2 | jerry       |   23 |
|  3 | haha        |   20 |
|  4 | sean        |   28 |
|  5 | zhangsan    |   26 |
|  6 | zhangsan    |   20 |
| 11 | qiuxiaotian |   20 |
+----+-------------+------+
7 rows in set (0.00 sec)

mysql>

12.修改wangwu的年龄为100

mysql> update student set  age='100' where name='wangwu';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from student where name='wangwu';
+----+--------+------+
| id | name   | age  |
+----+--------+------+
|  9 | wangwu |  100 |
+----+--------+------+
1 row in set (0.00 sec)

mysql>

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

mysql> delete   from student where name='zhangsan' and age<=20;
Query OK, 1 row affected (0.00 sec)

mysql> select * from student where  not name='zhangsan';  //使用not取反查看
+----+-------------+------+
| id | name        | age  |
+----+-------------+------+
|  1 | tom         |   20 |
|  2 | jerry       |   23 |
|  3 | haha        |   20 |
|  4 | sean        |   28 |
|  7 | lisi        |   50 |
|  8 | chenshuo    |   10 |
|  9 | wangwu      |  100 |
| 10 | qiuyi       |   15 |
| 11 | qiuxiaotian |   20 |
+----+-------------+------+
9 rows in set (0.00 sec)

mysql>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值