mysql基础

1.关系型数据库的介绍

1.1 数据结构模型

数据结构模型主要有:

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

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

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

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
  • 权限:privilege
  • 存储过程:procedure
  • 存储函数:function
  • 触发器:trigger
  • 事件调度器:event scheduler

1.4 SQL语句

SQL语句有三种类型:

  • DDL:Data Defination Language,数据定义语言
  • DML:Data Manipulation Language,数据操纵语言
  • DCL:Data Control Language,数据控制语言
SQL语句的类型 对应操作
DDL create:创建
drop:删除
alter:修改
DML insert:向表中插入数据
delete:删除表中的数据
update:更新表中的数据
select:查询表中的数据
DCL grant:授权
revoke:移除授权

2.MySQL的安装与配置

2.1 安装mysql

mysql安装方式有三种:

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

使用yum安装mysql

#配置mysql的yum源
[root@zzd139 ~]# wget http://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm
[root@zzd139 ~]# rpm -Uvh mysql57-community-release-el7-11.noarch.rpm 
warning: mysql57-community-release-el7-11.noarch.rpm: Header V3 DSA/SHA1 Signature, key ID 5072e1f5: NOKEY
Verifying...                          ################################# [100%]
Preparing...                          ################################# [100%]
Updating / installing...
   1:mysql57-community-release-el7-11 ################################# [100%]

#将yum仓库自带的mysql先禁用掉
[root@zzd139 ~]# dnf module disable mysql

#安装mysql5.7
[root@zzd139 ~]# dnf -y install mysql-community-server mysql-community-client mysql-community-common mysql-community-devel --nogpgcheck 

2.2 mysql配置

#将mysql设置为开机自启并且启动mysql
[root@zzd139 ~]# systemctl enable --now mysqld
[root@zzd139 ~]# systemctl status mysqld
● mysqld.service - MySQL Server
   Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
   Active: active (running) since Mon 2022-07-25 17:41:45 CST; 7s ago
     Docs: man:mysqld(8)
           http://dev.mysql.com/doc/refman/en/using-systemd.html
  Process: 4357 ExecStart=/usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid $MYSQLD_OPTS (code=exited, status=0/SUCCESS)
  Process: 4308 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
 Main PID: 4360 (mysqld)
    Tasks: 27 (limit: 5770)
   Memory: 291.9M
   CGroup: /system.slice/mysqld.service
           └─4360 /usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid

Jul 25 17:41:42 zzd139 systemd[1]: Starting MySQL Server...
Jul 25 17:41:45 zzd139 systemd[1]: Started MySQL Server.

#查看端口号
[root@zzd139 ~]# ss -antlp | grep mysql
LISTEN 0      80                 *:3306            *:*    users:(("mysqld",pid=4360,fd=21))  

#获取mysql的初始密码
[root@zzd139 ~]# cat /var/log/mysqld.log | grep password
2022-07-25T09:41:43.449315Z 1 [Note] A temporary password is generated for root@localhost: haaforZyu7-k
2022-07-25T09:43:00.066543Z 2 [Note] Access denied for user 'root'@'localhost' (using password: NO)

#使用初始密码登录到mysql命令行
[root@zzd139 ~]# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
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;	//更改mysql的密码等级
Query OK, 0 rows affected (0.00 sec)

mysql> set global validate_password_length=1;	//更改mysql的密码长度
Query OK, 0 rows affected (0.00 sec)

mysql> set password = password('zzd123!!');		//更改mysql的密码
Query OK, 0 rows affected, 1 warning (0.00 sec)

#退出mysql
mysql> exit;
Bye

#为了避免后期mysql自动升级,将最开始的yum源卸载
[root@zzd139 ~]# rpm -e mysql57-community-release 

2.3 mariadb安装

dnf -y install mariadb*

3.mysql的程序组成

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

3.1 mysql工具的使用

语法:mysql [OPTIONS] [database]

常用选项(OPTIONS):

-uUSERNAME 指定用户名,默认为root

-hHOST 指定服务器主机,默认为localhost,推荐使用ip地址

-pHOSTpassword 指定用户密码

-P 指定数据库监听端口

-V 查看当前使用的mysql版本

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

[root@zzd139 ~]# mysql -uroot -p

#注意,不推荐直接在命令行里直接用-pPASSWORD的方式登录,而是使用-p选项,然后交互式输入密码
[root@zzd139 ~]# mysql -uroot -pzzd123 -hlocalhost
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 16
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>


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


[root@zzd139 ~]# mysql -uroot -pzzd123 -e 'show databases;'
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

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

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

4.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。下面的表显示了需要的每个整数类型的存储和范围

类型 大小 范围(有符号) 范围(无符号) 用途
TINYINT 1 byte (-128,127) (0,255) 小整数值
SMALLINT 2 bytes (-32 768,32 767) (0,65 535) 大整数值
MEDIUMINT 3 bytes (-8 388 608,8 388 607) (0,16 777 215) 大整数值
INT或INTEGER 4 bytes (-2 147 483 648,2 147 483 647) (0,4 294 967 295) 大整数值
BIGINT 8 bytes (-9,223,372,036,854,775,808,9 223 372 036 854 775 807) (0,18 446 744 073 709 551 615) 极大整数值
FLOAT 4 bytes (-3.402 823 466 E+38,-1.175 494 351 E-38),0,(1.175 494 351 E-38,3.402 823 466 351 E+38) 0,(1.175 494 351 E-38,3.402 823 466 E+38) 单精度
浮点数值
DOUBLE 8 bytes (-1.797 693 134 862 315 7 E+308,-2.225 073 858 507 201 4 E-308),0,(2.225 073 858 507 201 4 E-308,1.797 693 134 862 315 7 E+308) 0,(2.225 073 858 507 201 4 E-308,1.797 693 134 862 315 7 E+308) 双精度 浮点数值
DECIMAL 对DECI
MAL(M,D) ,如果M>D,为M+2否则为D+2
依赖于M和D的值 依赖于M和D的值 小数

日期和时间类型

表示时间值的日期和时间类型为DATETIME、DATE、TIMESTAMP、TIME和YEAR。每个时间类型有一个有效值范围和一个"零"值,当指定不合法的MySQL不能表示的值时使用"零"值。TIMESTAMP类型有专有的自动更新特性,将在后面描述。

类型 大小( bytes) 范围 格式 用途
DATE 3 1000-01-01/9999-12-31 YYYY-MM-DD 日期值
TIME 3 '-838:59:59'/'838:59:59' HH:MM:SS 时间值或持续时间
YEAR 1 1901/2155 YYYY 年份值
DATETIME 8 1000-01-01 00:00:00/9999-12-31 23:59:59 YYYY-MM-DD HH:MM:SS 混合日期和时间值
TIMESTAMP 4 1970-01-01 00:00:00/2038 结束时间是第 2147483647 秒,北京时间 2038-1-19 11:14:07,格林尼治时间 2038年1月19日 凌晨 03:14:07 YYYYMMDD HHMMSS 混合日期和时间值,时间戳

字符串类型

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

类型 大小 用途
CHAR 0-255 bytes 定长字符串
VARCHAR 0-65535 bytes 变长字符串
TINYBLOB 0-255 bytes 不超过 255 个字符的二进制字符串
TINYTEXT 0-255 bytes 短文本字符串
BLOB 0-65 535 bytes 二进制形式的长文本数据
TEXT 0-65 535 bytes 长文本数据
MEDIUMBLOB 0-16 777 215 bytes 二进制形式的中等长度文本数据
MEDIUMTEXT 0-16 777 215 bytes 中等长度文本数据
LONGBLOB 0-4 294 967 295 bytes 二进制形式的极大文本数据
LONGTEXT 0-4 294 967 295 bytes 极大文本数据

5.mysql数据库操作

5.1DDL语句

5.1.1 数据库操作

#创建数据库
mysql> create database zic;
Query OK, 1 row affected (0.00 sec)

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

#删除数据库
mysql> drop database zic;
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)

5.1.2 表操作

#创建表
mysql> create database zic;			#创建数据库
Query OK, 1 row affected (0.00 sec)

mysql> use zic;					#进入数据库
Database changed

mysql> create table zzd(id int not null,name varchar(20),sex varchar(3));	#创建表
Query OK, 0 rows affected (0.01 sec)

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

#删除表
mysql> drop table zzd;
Query OK, 0 rows affected (0.01 sec)

mysql> show tables;
Empty set (0.00 sec)

5.1.3 用户操作

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

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

  • IP地址,如:172.16.12.129
  • 通配符
    • %:匹配任意长度的任意字符,常用于设置允许从任何主机登录
    • _:匹配任意单个字符
#创建用户
mysql> create user zic@'localhost' identified by 'zic123456';
Query OK, 0 rows affected (0.00 sec)

#使用上面创建的用户登录mysql
[root@zzd139 ~]# mysql -uzic -pzic123456 -hlocalhost;
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 20
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> drop user zic@'localhost';
Query OK, 0 rows affected (0.00 sec)

5.1.4 查看命令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 |
| 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 |
| utf16le  | UTF-16LE Unicode                | utf16le_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 |
| gb18030  | China National Standard GB18030 | gb18030_chinese_ci  |      4 |
+----------+---------------------------------+---------------------+--------+
41 rows in set (0.00 sec)


#查看当前数据库支持的所有存储引擎
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)
#上一条命令显示的比较乱,可以使用\G来以列的方式显示
mysql> show engines\G;
*************************** 1. row ***************************
      Engine: InnoDB
     Support: DEFAULT
     Comment: Supports transactions, row-level locking, and foreign keys
Transactions: YES
          XA: YES
  Savepoints: YES
*************************** 2. row ***************************
      Engine: MRG_MYISAM
     Support: YES
     Comment: Collection of identical MyISAM tables
Transactions: NO
          XA: NO
  Savepoints: NO
*************************** 3. row ***************************
      Engine: MEMORY
     Support: YES
     Comment: Hash based, stored in memory, useful for temporary tables
Transactions: NO
          XA: NO
  Savepoints: NO
…………


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

#不进入某数据库而列出其包含的所有表
mysql> show tables from zic;
+---------------+
| Tables_in_zic |
+---------------+
| zzd           |
+---------------+
1 row in set (0.00 sec)

#查看表的结构
mysql> desc zzd;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   |     | NULL    |       |
| name  | varchar(20) | YES  |     | NULL    |       |
| sex   | varchar(3)  | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

#查看zzd表的创建过程
mysql> show create table zzd;
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                            |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------+
| zzd   | CREATE TABLE `zzd` (
  `id` int(11) NOT NULL,
  `name` varchar(20) DEFAULT NULL,
  `sex` varchar(3) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

#查看zzd表的状态
mysql> show table status like 'zzd'\G;
*************************** 1. row ***************************
           Name: zzd
         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 21:41:13
    Update_time: NULL
     Check_time: NULL
      Collation: latin1_swedish_ci
       Checksum: NULL
 Create_options: 
        Comment: 
1 row in set (0.00 sec)

5.1.5获取帮助

#获取创建数据库的帮助
mysql> help create database;
Name: 'CREATE DATABASE'
Description:
Syntax:
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
    [create_option] ...

create_option: [DEFAULT] {
    CHARACTER SET [=] charset_name
  | COLLATE [=] collation_name
}

CREATE DATABASE creates a database with the given name. To use this
statement, you need the CREATE privilege for the database. CREATE
SCHEMA is a synonym for CREATE DATABASE.

URL: https://dev.mysql.com/doc/refman/5.7/en/create-database.html

5.2 DML操作

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

5.2.1 insert语句

#向表zzd中插入数据
mysql> use zic;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed

mysql> insert into zzd(id,name,sex) values(1,'zhangsan','M'),(2,'lisi','W'),(3,'wangwu','M'),(4,'lisa','W');
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

5.2.2 select语句

字段column表示法

表示符 代表什么
* 所有字段
as 字段别名,当表明很长时用别名代替
#查看zzd表的所有字段
mysql> select * from zzd;
+----+----------+------+
| id | name     | sex  |
+----+----------+------+
|  1 | zhangsan | M    |
|  2 | lisi     | W    |
|  3 | wangwu   | M    |
|  4 | lisa     | W    |
+----+----------+------+
4 rows in set (0.00 sec)

#查看表zzd的name和sex字段,并且分别用“姓名”和“性别”做别名代替
mysql> select name as 姓名,sex as 性别 from zzd;
+----------+--------+
| 姓名     | 性别   |			$(这种别名替换只是临时的,下次执行select就没了)
+----------+--------+
| zhangsan | M      |
| lisi     | W      |
| wangwu   | M      |
| lisa     | W      |
+----------+--------+
4 rows in set (0.00 sec)

条件判断语句where

操作类型 常用操作符
操作符 >,<,>=,<=,=,!=
BETWEEN column# AND column#
LIKE:模糊匹配
RLIKE:基于正则表达式进行模式匹配
IS NOT NULL:非空
IS NULL:空
条件逻辑操作 and
or
not
#使用where判断语句查询zzd表中id大于2的记录
mysql> select * from zzd where id > 2;
+----+--------+------+
| id | name   | sex  |
+----+--------+------+
|  3 | wangwu | M    |
|  4 | lisa   | W    |
+----+--------+------+
2 rows in set (0.01 sec)

#使用where判断语句查询zzd表中id小于4的记录
mysql> select * from zzd where id < 4;
+----+----------+------+
| id | name     | sex  |
+----+----------+------+
|  1 | zhangsan | M    |
|  2 | lisi     | W    |
|  3 | wangwu   | M    |
+----+----------+------+
3 rows in set (0.00 sec)

#使用where判断语句查询zzd表中id大于等于2的记录
mysql> select * from zzd where id >= 2;
+----+--------+------+
| id | name   | sex  |
+----+--------+------+
|  2 | lisi   | W    |
|  3 | wangwu | M    |
|  4 | lisa   | W    |
+----+--------+------+
3 rows in set (0.00 sec)

#使用where判断语句查询zzd表中id小于等于2的记录
mysql> select * from zzd where id <= 2;
+----+----------+------+
| id | name     | sex  |
+----+----------+------+
|  1 | zhangsan | M    |
|  2 | lisi     | W    |
+----+----------+------+
2 rows in set (0.00 sec)

#使用where判断语句查询zzd表中name等于'lisa'的记录
mysql> select * from zzd where name = 'lisa';
+----+------+------+
| id | name | sex  |
+----+------+------+
|  4 | lisa | W    |
+----+------+------+
1 row in set (0.01 sec)

#使用where判断语句查询zzd表中id字段的范围在2——4之间的记录
mysql> select * from zzd where id between 2 and 4;
+----+--------+------+
| id | name   | sex  |
+----+--------+------+
|  2 | lisi   | W    |
|  3 | wangwu | M    |
|  4 | lisa   | W    |
+----+--------+------+
3 rows in set (0.00 sec)

#模糊查找表zzd中匹配'%g%'的的记录
mysql> select * from zzd where name like '%g%';
+----+----------+------+
| id | name     | sex  |
+----+----------+------+
|  1 | zhangsan | M    |
|  3 | wangwu   | M    |
+----+----------+------+
2 rows in set (0.00 sec)

#查询表zzd中name字段不为空的记录
mysql> select * from zzd where name is not null;
+----+----------+------+
| id | name     | sex  |
+----+----------+------+
|  1 | zhangsan | M    |
|  2 | lisi     | W    |
|  3 | wangwu   | M    |
|  4 | lisa     | W    |
+----+----------+------+
4 rows in set (0.00 sec)

#查询表zzd中name字段为空的记录
mysql> select * from zzd where name is null;
Empty set (0.00 sec)

#查询表zzd中id字段为等于2并且name字段为'lisi'的记录
mysql> select * from zzd where id = 2 and name = 'lisi';
+----+------+------+
| id | name | sex  |
+----+------+------+
|  2 | lisi | W    |
+----+------+------+
1 row in set (0.00 sec)

#查询表zzd中id字段为等于4或者name字段为'lisi'的记录
mysql> select * from zzd where id = 4 or name = 'lisi';
+----+------+------+
| id | name | sex  |
+----+------+------+
|  2 | lisi | W    |
|  4 | lisa | W    |
+----+------+------+
2 rows in set (0.00 sec)

#查询zzd表name字段不是'zhangsan'的字段
mysql> select * from zzd where not name = 'zhangsan'
    -> ;
+----+--------+------+
| id | name   | sex  |
+----+--------+------+
|  2 | lisi   | W    |
|  3 | wangwu | M    |
|  4 | lisa   | W    |
+----+--------+------+
3 rows in set (0.00 sec)

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个结果
#对zzd表以字段id进行升序排序
mysql> select * from zzd order by id;
+----+----------+------+
| id | name     | sex  |
+----+----------+------+
|  1 | zhangsan | M    |
|  2 | lisi     | W    |
|  3 | wangwu   | M    |
|  4 | lisa     | W    |
+----+----------+------+
4 rows in set (0.00 sec)

#对zzd表以字段id进行降序排序
mysql> select * from zzd order by id desc;
+----+----------+------+
| id | name     | sex  |
+----+----------+------+
|  4 | lisa     | W    |
|  3 | wangwu   | M    |
|  2 | lisi     | W    |
|  1 | zhangsan | M    |
+----+----------+------+
4 rows in set (0.00 sec)

#对zzd表以字段id进行升序排序只去前两条记录
mysql> select * from zzd order by id limit 2;
+----+----------+------+
| id | name     | sex  |
+----+----------+------+
|  1 | zhangsan | M    |
|  2 | lisi     | W    |
+----+----------+------+
2 rows in set (0.00 sec)

#对zzd表以字段id进行逆序排序并略过前两条记录,取后面后面一条记录,也就是第三条记录
mysql> select * from zzd order by id desc limit 2,1;
+----+------+------+
| id | name | sex  |
+----+------+------+
|  2 | lisi | W    |
+----+------+------+
1 row in set (0.00 sec)

5.2.3 update语句

#给表zzd新添加一个字段idnum
mysql> alter table zzd add idnum varchar(20);
Query OK, 0 rows affected (0.04 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc zzd;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   |     | NULL    |       |
| name  | varchar(20) | YES  |     | NULL    |       |
| sex   | varchar(3)  | YES  |     | NULL    |       |
| idnum | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

mysql> select * from zzd;
+----+----------+------+-------+
| id | name     | sex  | idnum |
+----+----------+------+-------+
|  1 | zhangsan | M    | NULL  |
|  2 | lisi     | W    | NULL  |
|  3 | wangwu   | M    | NULL  |
|  4 | lisa     | W    | NULL  |
+----+----------+------+-------+
4 rows in set (0.00 sec)

#将表zzd中name为'zhangsan'的idnum字段改为‘123456'
mysql> update zzd set idnum = '123456' where name = 'zhangsan';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from zzd;
+----+----------+------+--------+
| id | name     | sex  | idnum  |
+----+----------+------+--------+
|  1 | zhangsan | M    | 123456 |
|  2 | lisi     | W    | NULL   |
|  3 | wangwu   | M    | NULL   |
|  4 | lisa     | W    | NULL   |
+----+----------+------+--------+
4 rows in set (0.01 sec)

5.2.4 delete语句

#创建zzdtest表,有字段id,name,age,id字段为主键并且自动增长
mysql> create table zzdtest(id int not null primary key auto_increment,name varchar(20),age tinyint);
Query OK, 0 rows affected (0.01 sec)

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

#插入几条数据,id字段不用管
mysql> insert into zzdtest(name,age) values('lisa',18),('tom',19),('jreey',18),('natasha',20);
Query OK, 4 rows affected (0.01 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select * from zzdtest;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | lisa    |   18 |		$(id字段自动增长)
|  2 | tom     |   19 |
|  3 | jreey   |   18 |
|  4 | natasha |   20 |
+----+---------+------+
4 rows in set (0.00 sec)

#删除name为'tom'的记录
mysql> delete from zzdtest where name = 'tom';
Query OK, 1 row affected (0.00 sec)

mysql> select * from zzdtest;
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | lisa    |   18 |
|  3 | jreey   |   18 |
|  4 | natasha |   20 |
+----+---------+------+
3 rows in set (0.00 sec)

#删除整张表的所有记录
mysql> delete from zzdtest;
Query OK, 3 rows affected (0.00 sec)

mysql> select * from zzdtest;
Empty set (0.00 sec)
$(只是删除了表的记录,并没有删除表或表的结构)
mysql> desc zzdtest;	
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(20) | YES  |     | NULL    |                |
| age   | tinyint(4)  | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

5.2.5 truncate语句

truncate与delete的区别:

语句类型 特点
delete DELETE删除表内容时仅删除内容,但会保留表结构
DELETE语句每次删除一行,并在事务日志中为所删除的每行记录一项
可以通过回滚事务日志恢复数据
非常占用空间
truncate 删除表中所有数据,且无法恢复
表结构、约束和索引等保持不变,新添加的行计数值重置为初始值
执行速度比DELETE快,且使用的系统和事务日志资源少
通过释放存储表数据所用的数据页来删除数据,并且只在事务日志中记录页的释放
对于有外键约束引用的表,不能使用TRUNCATE TABLE删除数据
不能用于加入了索引视图的表
#重新对zzdtest表插入数据
mysql> insert into zzdtest(name,age) values('lisa',18),('tom',19),('jreey',18),('natasha',20);
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select * from zzdtest;
$(id是自动增长,但是是从5开始的,这是用为delete删除并没有完全删除,而是会存在与日志中,后面可以恢复,所以不会重置自动增长)
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  5 | lisa    |   18 |		
|  6 | tom     |   19 |			
|  7 | jreey   |   18 |
|  8 | natasha |   20 |
+----+---------+------+
4 rows in set (0.00 sec)

#删除zzdtest表中的所有记录
mysql> truncate zzdtest;
Query OK, 0 rows affected (0.01 sec)

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

#重新再插入数据
mysql> insert into zzdtest(name,age) values('lisa',18),('tom',19),('jreey',18),('natasha',20);
Query OK, 4 rows affected (0.01 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select * from zzdtest;
$(truncate删除是不可恢复的,会重置自动增长,所以truncate语句删除需要慎用)
+----+---------+------+
| id | name    | age  |
+----+---------+------+
|  1 | lisa    |   18 |
|  2 | tom     |   19 |
|  3 | jreey   |   18 |
|  4 | natasha |   20 |
+----+---------+------+
4 rows in set (0.00 sec)

5.3 DCL操作

5.3.1 创建授权grant

权限类型(priv_type)

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

指定要操作的对象db_name.table_name

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

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

#授权zzd用户在数据库本机上登录访问所有数据库
mysql> grant all on *.* to zzd@'localhost' identified by 'zzd123';
Query OK, 0 rows affected, 1 warning (0.00 sec)
#刷新授权
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

#查看zzd@'localhost'的授权
mysql> show grants for zzd@'localhost';
+--------------------------------------------------+
| Grants for zzd@localhost                         |
+--------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'zzd'@'localhost' |
+--------------------------------------------------+
1 row in set (0.00 sec)

#使用用户zzd@'localhost'登录mysql
[root@zzd139 ~]# mysql -uzzd -p -hlocalhost
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
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> 

5.3.2 取消授权revoke

#取消zzd用户在数据库本机上登录访问所有数据库的权限
mysql> revoke all on *.* from zzd@'localhost';
Query OK, 0 rows affected (0.00 sec)

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

#查看授权
mysql> show grants for zzd@'localhost';
+-----------------------------------------+
| Grants for zzd@localhost                |
+-----------------------------------------+
| GRANT USAGE ON *.* TO 'zzd'@'localhost' |
+-----------------------------------------+
1 row in set (0.00 sec)

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

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

mysql远程连接工具

#新建一个用户zzd@'192.168.169.1'对所有数据库拥有所有权限
mysql> grant all on *.* to zzd@'192.168.169.1' identified by 'zzdlink';
Query OK, 0 rows affected, 1 warning (0.00 sec)

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

打开远程连接工具,新建连接

点击测试连接,显示连接成功,可点击确定进行连接

实战案例

1.搭建mysql服务

#配置mysql的yum源
[root@zzd139 ~]# wget http://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm
[root@zzd139 ~]# rpm -Uvh mysql57-community-release-el7-11.noarch.rpm 
warning: mysql57-community-release-el7-11.noarch.rpm: Header V3 DSA/SHA1 Signature, key ID 5072e1f5: NOKEY
Verifying...                          ################################# [100%]
Preparing...                          ################################# [100%]
Updating / installing...
   1:mysql57-community-release-el7-11 ################################# [100%]

#将yum仓库自带的mysql先禁用掉
[root@zzd139 ~]# dnf module disable mysql

#安装mysql5.7
[root@zzd139 ~]# dnf -y install mysql-community-server mysql-community-client mysql-community-common mysql-community-devel --nogpgcheck 

[root@zzd139 ~]# cat /var/log/mysqld.log | grep password
2022-07-25T09:41:43.449315Z 1 [Note] A temporary password is generated for root@localhost: haaforZyu7-k
2022-07-25T09:43:00.066543Z 2 [Note] Access denied for user 'root'@'localhost' (using password: NO)

#使用查找到的密码登录mysql
[root@zzd139 ~]# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
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> 

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

+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(100) | NO   |     | NULL    |                |
| age   | tinyint(4)   | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
mysql> create database zzd;
Query OK, 1 row affected (0.00 sec)
mysql> use zzd;
Database changed
mysql> create table student(id int not null primary key auto_increment,name varchar(20),age tinyint(2));
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(20) | YES  |     | NULL    |                |
| age   | tinyint(2)  | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

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

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

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

+----+-------------+------+
| 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 |
+----+-------------+------+
mysql> insert into student(name,age) values('tom',20),('jerry',23),('wangqing',25),('sean',28),('zhangshan',26),('zhangshan',20),('lisi',null),('chenshuo',10),('wangwu',3),('qiuyi',15),('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 | 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.01 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)

6.以age字段降序排序

mysql> select * from student order by age desc;
+----+-------------+------+
| id | name        | age  |
+----+-------------+------+
|  7 | lisi        |   50 |
|  4 | sean        |   28 |
|  5 | zhangshan   |   26 |
|  3 | wangqing    |   25 |
|  2 | jerry       |   23 |
|  1 | tom         |   20 |
|  6 | zhangshan   |   20 |
| 11 | qiuxiaotian |   20 |
| 10 | qiuyi       |   15 |
|  8 | chenshuo    |   10 |
|  9 | wangwu      |    3 |
+----+-------------+------+
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 |
|  4 | sean      |   28 |
|  5 | zhangshan |   26 |
|  3 | wangqing  |   25 |
+----+-----------+------+
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 name = 'zhangshan' and age > 20;
+----+-----------+------+
| id | name      | age  |
+----+-----------+------+
|  5 | zhangshan |   26 |
+----+-----------+------+
1 row 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> 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)

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

mysql> select * from student;
+----+-------------+------+
| id | name        | age  |
+----+-------------+------+
|  1 | tom         |   20 |
|  2 | jerry       |   23 |
|  3 | wangqing    |  100 |
|  4 | sean        |   28 |
|  5 | zhangshan   |   26 |
|  7 | lisi        |   50 |
|  8 | chenshuo    |   10 |
|  9 | wangwu      |    3 |
| 10 | qiuyi       |   15 |
| 11 | qiuxiaotian |   20 |
+----+-------------+------+
10 rows in set (0.00 sec)
posted @ 2022-08-01 20:36  Zic师傅  阅读(22)  评论(0编辑  收藏  举报