资讯详情

mysql基础

mysql基础

  1. 介绍关系数据库 1.1 数据结构模型 1.2 RDBMS专业名词 1.3 关系数据库中常见的组件 1.4 SQL语句

  2. mysql安装与配置 2.1 mysql安装 2.2 mysql配置

  3. mysql的程序组成 3.1 mysql工具使用 3.2 两种服务器监控socket地址

    1. mysql数据库操作 4.1 DDL操作 4.1.1 数据库操作 4.1.2 表操作 4.1.3 用户操作 4.1.4 查看命令SHOW 4.1.5 获取帮助 4.2 DML操作 4.2.1 INSERT语句 4.2.2 SELECT语句 4.2.3 update语句 4.2.4 delete语句 4.2.5 truncate语句 4.3 DCL操作 4.3.1 创建授权grant 4.3.2 查看授权 4.3.3 取消授权REVOKE 实战案例

1. 介绍关系数据库

1.1 数据结构模型

数据结构模型主要包括:

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

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

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

1.2 RDBMS专业名词

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

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

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

:constraint,向数据表提供的数据应遵守限制

主键约束:一个或多个字段的组合,填写的数据必须能够在本表中识别出行。并且必须提供数据,而不是空的(NOT NULL)。 

一个表只能存在一个 唯一键约束:一个或多个字段的组合,填写的数据必须能够在本表中标记本行。(NULL) 一个表可以存在多个 外键约束:一个表中的某字段可填入数据取决于另一个表的主键已有的数据 检查性约束 索引:复制表中一个或多个字段中的数据,并按特定顺序存储

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

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

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

1.4 SQL语句

SQL句子有三种:

DDL:Data Defination Language,语言的数据定义 DML:Data Manipulation Language,数据操作语言 DCL:Data Control Language,语言的数据控制

SQL语句类型 对应操作

CREATE:创建 DROP:删除 ALTER:修改

DML

INSERT:将数据插入到表中 DELETE:删除表中的数据 UPDATE:更新表中的数据 SELECT:查询表中的数据

DCL

GRANT:授权 REVOKE:移除授权

2.1 mysql安装

mysql有三种安装方法:

:编译安装 :扩展到特定路径,简单配置后即可使用 : rpm:有两种 OS Vendor:操作系统发行商提供的项目正式提供 deb #配置mysql的yum源 wget -O /usr/src/mysql57-community-release-el7-10.noarch.rpm \http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm

使用rpm -Uch 更新软件包 rpm -Uvh /usr/src/mysql57-community-release-el7-10.noarch.rpm 效果:

[root@localhost ~]# wget http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm [root@localhost ~]# ls anaconda-ks.cfg  mysql57-community-release-el7-10.noarch.rpm [root@localhost ~]# rpm -Uvh mysql57-community-release-el7-10.noarch.rpm  [root@http ~]# ls /etc/yum.repos.d/ | grep mysql-* mysql-community.repo mysql-community-source.repo 

#安装mysql5.7 此时首先关闭模块

[root@http ~]# yum module disable mysql Last metadata expiration check: 0:01:51 ago on Sat 23 Jul 2022 11:43:48 AM CST. Dependencies resolved. ======================================================================  Package         Architecture   Version         Repository       Size ====================================================================== Disabling modules:  mysql                                                                 Transaction Summary ======================================================================  Is this ok [y/N]: y Complete! 

这里安装mysql环境配置 yum -y install mysql-community-server mysql-community-client mysql-community-common mysql-community-devel --nogpgcheck (不检查安装的合法性)

[root@http ~]# yum -y install mysql-community-server mysql-community-client mysql-community-common mysql-community-devel --nogpgcheck Last metadata expiration check: 0:03:55 ago on Sat 23 Jul 2022 12:07:07 PM CST. Package mysql-community-server-5.7.38-1.el7.x86_64 is already installed. Package mysql-community-client-5.7.38-1.el7.x86_64 is already installed. Package mysql-community-common-5.7.38-1.el7.x86_64 is already installed. Package mysql-community-devel-5.7.38-1.el7.x86_64 is already installed. Dependencies resolved. Nothing to do. Complete!  

2.2 mysql配置

启动mysql并设置自动启动启动

sstemctl enable --now mysqld systemctl status mysqld

[root@http ~]# systemctl enable --now mysqld
[root@http ~]# systemctl status mysqld
● mysqld.service - MySQL Server
   Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; v>
   Active: active (running) 

确保3306端口已经监听起来

ss -antl

[root@http ~]# ss -antl
State  Recv-Q Send-Q   Local Address:Port   Peer Address:Port Process 
LISTEN 0      128            0.0.0.0:80          0.0.0.0:*            
LISTEN 0      128            0.0.0.0:22          0.0.0.0:*            
LISTEN 0      80                   *:3306              *:*            
LISTEN 0      128               [::]:22             [::]:*  

在日志文件中找出临时密码

grep “password” /var/log/mysqld.log

[root@http ~]# grep "password" /var/log/mysqld.log 
2022-07-23T04:11:40.348186Z 1 [Note] A temporary password is generated for root@localhost: p2u4SAs%hf/j

#使用获取到的临时密码登录mysql

[root@localhost ~]# mysql -uroot -p
Enter password:    		 //此处输入密码,可以直接复制你的密码粘贴至此处,也可手动输入
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
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> 		 //看到有这样的标识符则表示成功登录了

//修改mysql登录密码

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

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

mysql> alter user 'root'@'localhost' identified by 'lty123';
Query OK, 0 rows affected (0.00 sec)

mysql> exit
Bye
[root@http ~]# mysql -uroot -plty123
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 5
Server version: 5.7.38 MySQL Community Server (GPL)

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> 

//为避免mysql自动升级,这里需要卸载最开始安装的yum源

[root@http ~]# rpm -e mysql57-community-release

二、yum安装mariadb

[root@http ~]# yum -y install mariadb*
[root@http ~]# rpm -qa | grep mariadb*
mariadb-server-galera-10.3.28-1.module_el8.3.0+757+d382997d.x86_64
mariadb-test-10.3.28-1.module_el8.3.0+757+d382997d.x86_64
mariadb-errmsg-10.3.28-1.module_el8.3.0+757+d382997d.x86_64
略

设置开机自启动,并进入mariadb

[root@http ~]# systemctl enable --now mariadb.service
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@http ~]# 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 statement.

MariaDB [(none)]> 

为mariadb修改密码

MariaDB [(none)]> set password = password('lty123');
Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]> exit
Bye
[root@http ~]# mysql -uroot -plty123
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)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.001 sec)

3. mysql的程序组成

客户端 mysql:CLI 交互式客户端程序

修改密码 mysql_secure_installation:安全初始化,强烈建议安装完以后执行此命令

mysqldump:mysql备份工具 myqladmin 服务器端 mysqld

3.1 mysql工具使用

//语法:mysql [OPTIONS] [database] //常用的OPTIONS:

-uUSERNAME //指定用户名,默认为root 可以指定登录也可以不指定

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

[root@http ~]# mysql -V
mysql  Ver 14.14 Distrib 5.7.38, for Linux (x86_64) using  EditLine wrapper
[root@http ~]# mysql -uroot -plty123 -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 7
Server version: 5.7.38 MySQL Community Server (GPL)

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> 

//注意,不推荐直接在命令行里直接用-pPASSWORD的方式登录,而是使用-p选项,然后交互式输入密码

[root@http ~]# mysql -uroot -p -h127.0.0.1
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.7.38 MySQL Community Server (GPL)

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> 

-e //不登录mysql执行sql语句后退出,常用于脚本

[root@http ~]# mysql -uroot -p -h127.0.0.1 -e 'show databases;'
Enter password: 
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

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

socket类型 说明 ip socket 默认监听在tcp的3306端口,支持远程通信 支持ip地址访问

unix sock 监听在sock文件上(/tmp/mysql.sock,/var/lib/mysql/mysql.sock) 仅支持文件本地通信

server地址只能是:localhost,127.0.0.1

20-24

4. mysql数据库操作

4.1 DDL操作

4.1.1 数据库操作

//创建数据库 //语法:CREATE DATABASE [IF NOT EXISTS] ‘DB_NAME’; //创建数据库 lty

mysql> create database if not exists lty;
Query OK, 1 row affected (0.00 sec)

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

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| lty                |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)
//删除数据库

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

mysql> drop database if exists lty;
Query OK, 0 rows affected (0.00 sec)

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

4.1.2 表操作

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

mysql> CREATE DATABASE wangqingge;      //
Query OK, 1 row affected (0.00 sec)

//进入wangqingge数据库
mysql> use lty;
Database changed

//创建lty表结构
mysql> create table hh (id int not null,name varchar(100) not null,age tinyint);
Query OK, 0 rows affected (0.01 sec)


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

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

mysql> drop table hh;
Query OK, 0 rows affected (0.00 sec)

mysql> show tables;
Empty set (0.00 sec)

4.1.3 用户操作

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

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

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

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

//创建数据库用户lty

mysql> create user 'lty'@'127.0.0.1' identified by 'lty123';
Query OK, 0 rows affected (0.00 sec)

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

[root@http ~]# mysql -ulty -plty123 -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 12
Server version: 5.7.38 MySQL Community Server (GPL)

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> 

**//语法:DROP USER ‘username’@‘host’;

mysql> drop user 'lty'@'127.0.0.1';
Query OK, 0 rows affected (0.00 sec)
mysql> exit
Bye
[root@http ~]# mysq**l -ulty -plty123 -h127.0.0.1
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1045 (28000): Access denied for user 'lty'@'localhost' (using password: YES)

查看当前以行显示用户

4.1.4 查看命令SHOW

mysql> SHOW CHARACTER SET; //查看支持的所有字符集

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
......

mysql> SHOW ENGINES; //查看当前数据库支持的所有存储引擎

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; //查看数据库信息

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| lty                |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

mysql> SHOW TABLES FROM wangqingge; //不进入某数据库而列出其包含的所有表

mysql> show tables from lty;
+---------------+
| Tables_in_lty |
+---------------+
| hh            |
+---------------+
1 row in set (0.00 sec)
//查看表结构
//语法:DESC [db_name.]table_name;
mysql> desc hh;
+-------+--------------+------+-----+---------+-------+
| 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)

//查看某表的创建命令 //语法:SHOW CREATE TABLE table_name;

mysql> show create table hh;
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                        |
+-------+-----------------------------------------------------------------------------------------------------------------------------------------------------+
| hh    | CREATE TABLE `hh` (
  `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 lty; //进入数据库lty Database changed

mysql> show table status like 'hh'\G
*************************** 1. row ***************************
           Name: hh
         Engine: InnoDB
        Version: 10
     Row_format: Dynamic
           Rows: 2
 Avg_row_length: 8192
    Data_length: 16384
Max_data_length: 0
   Index_length: 0
      Data_free: 0
 Auto_increment: NULL
    Create_time: 2022-07-25 16:34:53
    Update_time: NULL
     Check_time: NULL
      Collation: latin1_swedish_ci
       Checksum: NULL
 Create_options: 
        Comment: 
1 row in set (0.00 sec)

4.1.5 获取帮助

//获取命令使用帮助

//语法:HELP keyword;
mysql> help create table;
Name: 'CREATE TABLE'
Description:
Syntax:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    (create_definition,...)
    [table_options]
    [partition_options]

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    [(create_definition,...)]
    [table_options]
    [partition_options]
    [IGNORE | REPLACE]
    [AS] query_expression

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    { LIKE old_tbl_name | (LIKE old_tbl_name) }
 ......
 ......

4.2 DML操作

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

4.2.1 INSERT语句

//DML操作之增操作insert //语法:INSERT [INTO] table_name [(column_name,…)] {VALUES | VALUE} (value1,…),(…),…

mysql> insert into hh (id,name,age) value (1,'ww',20);
Query OK, 1 row affected (0.01 sec)

mysql> select * from hh;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | ww   |   20 |
+----+------+------+
1 row in set (0.00 sec)

//多次插入

mysql> insert into hh (id,name,age) values (2,'q',21),(3,'w',22),(4,'e',23);
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from hh;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | ww   |   20 |
|  2 | q    |   21 |
|  3 | w    |   22 |
|  4 | e    |   23 |
+----+------+------+
4 rows in set (0.00 sec)

4.2.2 SELECT语句

字段column表示法 表示符 代表什么? 所有字段

as 字段别名,如col1 AS alias1 当表名很长时用别名代替

条件判断语句

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

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

//DML操作之查操作select

//语法:SELECT column1,column2,… FROM table_name [WHERE clause] [ORDER BY ‘column_name’ [DESC]] [LIMIT [m,]n];

mysql> select * from hh;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | ww   |   20 |
|  2 | q    |   21 |
|  3 | w    |   22 |
|  4 | e    |   23 |
+----+------+------+
4 rows in set (0.00 sec)

查询单个字段
mysql> select name from hh;
+------+
| name |
+------+
| ww   |
| q    |
| w    |
| e    |
+------+
4 rows in set (0.01 sec)

以年纪字段进行正排序
mysql> select * from hh order by age;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | ww   |   20 |
|  2 | q    |   21 |
|  3 | w    |   22 |
|  4 | e    |   23 |
+----+------+------+
4 rows in set (0.00 sec)

以年纪进行倒叙排序
mysql> select * from hh order by age desc;
+----+------+------+
| id | name | age  |
+----+------+------+
|  4 | e    |   23 |
|  3 | w    |   22 |
|  2 | q    |   21 |
|  1 | ww   |   20 |
+----+------+------+
4 rows in set (0.00 sec)

查询处于字段前三的数据
mysql> select * from hh order by age limit 3;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | ww   |   20 |
|  2 | q    |   21 |
|  3 | w    |   22 |
+----+------+------+
3 rows in set (0.00 sec)

忽略查询以第一个数字开头的
mysql> select * from hh order by age limit 2,3;
+----+------+------+
| id | name | age  |
+----+------+------+
|  3 | w    |   22 |
|  4 | e    |   23 |
+----+------+------+
2 rows in set (0.00 sec)


查询当前年纪大于该数字的字段
mysql> select * from hh where age >= 22;
+----+------+------+
| id | name | age  |
+----+------+------+
|  3 | w    |   22 |
|  4 | e    |   23 |
+----+------+------+
2 rows in set (0.01 sec)

查询当前年纪大于该数字的字段和指定用户名
mysql> select * from hh where age >= 22 and name = 'e';
+----+------+------+
| id | name | age  |
+----+------+------+
|  4 | e    |   23 |
+----+------+------+
1 row in set (0.01 sec)

查询年纪之间的区间值
mysql> select * from hh where age between 20 and 22;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | ww   |   20 |
|  2 | q    |   21 |
|  3 | w    |   22 |
+----+------+------+
3 rows in set (0.01 sec)

不允许age字段为空
mysql> select * from wangqing where age is not null;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | tom       |   20 |
|  2 | jerry     |   23 |
|  3 | wangqing  |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
+----+-----------+------+
6 rows in set (0.00 sec)

只显示为空的字段
mysql> select * from hh where age is null;
+----+------+------+
| id | name | age  |
+----+------+------+
|  4 | r    | NULL |
+----+------+------+
1 row in set (0.00 sec)

4.2.3 update语句

//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 wangqing;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  1 | tom       |   20 |
|  2 | jerry     |   23 |
|  3 | wangqing  |   25 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  6 | zhangshan |   20 |
|  7 | lisi      | NULL |
+----+-----------+------+
7 rows in set (0.00 sec)

为非空字段添加数值
mysql> update hh set age = 24 where name ='r';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0
0

mysql> select * from hh where name = 'r';
+----+------+------+
| id | name | age  |
+----+------+------+
|  4 | r    |   24 |
+----+------+------+
1 row in set (0.00 sec)

4.2.4 delete语句

//DML操作之删操作delete //语法:DELETE FROM table_name [WHERE clause] [ORDER BY ‘column_name’ [DESC]] [LIMIT [m,]n];

mysql> select * from hh;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | ww   |   20 |
|  2 | q    |   21 |
|  3 | w    |   22 |
|  4 | e    |   23 |
|  4 | r    |   24 |
+----+------+------+
5 rows in set (0.00 sec)

//删除某条记录
mysql> delete from hh where name = 'r';
Query OK, 1 row affected (0.00 sec)

mysql> select * from hh;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | ww   |   20 |
|  2 | q    |   21 |
|  3 | w    |   22 |
|  4 | e    |   23 |
+----+------+------+
4 rows in set (0.00 sec)


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

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

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

4.2.5 truncate语句

truncate与delete的区别: 语句类型 特点 >delete DELETE删除表内容时仅删除内容,但会保留表结构 DELETE语句每次删除一行,并在事务日志中为所删除的每行记录一项 可以通过回滚事务日志恢复数据 非常占用空间

truncate 删除表中所有数据,且无法恢复 表结构、约束和索引等保持不变,新添加的行计数值重置为初始值 执行速度比DELETE快,且使用的系统和事务日志资源少 通过释放存储表数据所用的数据页来删除数据,并且只在事务日志中记录页的释放 对于有外键约束引用的表,不能使用TRUNCATE TABLE删除数据 不能用于加入了索引视图的表

//语法:TRUNCATE table_name;

mysql> select * from hh;
+----+------+------+
| id | name | age  |
+----+------+------+
|  4 | r    | NULL |
|  1 | w    |   22 |
|  3 | r    |   24 |
+----+------+------+
3 rows in set (0.00 sec)

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

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

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

4.3 DCL操作

4.3.1 创建授权grant

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

指定要操作的对象db_name.table_name 表示方式 意义 . 所有库的所有表 db_name 指定库的所有表 db_name.table_name 指定库的指定表

WITH GRANT OPTION:被授权的用户可将自己的权限副本转赠给其他用户,说白点就是将自己的权限完全复制给另一个用户。不建议使用。

GRANT priv_type,… ON [object_type] db_name.table_name TO ‘username’@‘host’ [IDENTIFIED BY ‘password’] [WITH GRANT OPTION];

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| lty                |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)


//授权wangqing用户在数据库本机上登录访问所有数据库
mysql> GRANT ALL ON *.* TO 'wangqing'@'localhost' IDENTIFIED BY 'wangqing123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)

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

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

//授权wangqing用户在所有位置上远程登录访问wangqingge数据库
mysql> GRANT ALL ON *.* TO 'wangqing'@'%' IDENTIFIED BY 'wangqing123!';
Query OK, 0 rows affected, 1 warning (0.00 sec)

4.3.2 查看授权

//查看当前登录用户的授权信息
mysql> SHOW GRANTS;
+---------------------------------------------------------------------+
| Grants for root@localhost                                           |
+---------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION |
| GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION        |
+---------------------------------------------------------------------+
2 rows in set (0.00 sec)

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

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

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

4.3.3 取消授权REVOKE

//语法:REVOKE priv_type,… ON db_name.table_name FROM ‘username’@‘host’;

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

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

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

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

mysql> FLUSH PRIVILEGES;

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

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| lty                |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

mysql> create table student (id int primary key auto_increment,name varchar(100),age varchar(4));
Query OK, 0 rows affected (0.01 sec)

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

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

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

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

mysql> insert into student (name,age) values ('tom',20),('jerry',23),('wangqing',25),('sean',28),('zhangshan',26),('zhangshan',20),('liisi',null)
Query OK, 11 rows affected (0.03 sec)
Records: 11  Duplicates: 0  Warnings: 0

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

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

6.以age字段降序排序

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

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

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

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

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

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

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

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

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

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

mysql> select * from student where age between 23 and 30;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  2 | jerry     | 23   |
|  3 | wangqing  | 25   |
|  4 | sean      | 28   |
|  5 | zhangshan | 26   |
+----+-----------+------+
4 rows in set (0.00 sec)

12.修改wangwu的年龄为100

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

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

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

mysql> delete from student where name = 'zhangshan' and age >= 20;
Query OK, 2 rows affected (0.00 sec)
mysql> select * from student where name = 'zhangshan';
Empty set (0.00 sec)

标签: hf角插接连接器

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台