mysql查询名词_mysql一些了解的名词

### 视图(了解)

* 什么是视图

```python

"""

视图就是通过查询得到一张虚拟表,然后保存下来,下次可以直接使用

其实视图也是表

"""

```

* 为什么要用视图

```python

"""

如果要频繁的操作一张虚拟表(拼表组成的),你就可以制作成视图 后续直接操作

"""

```

* 如何操作

```python

# 固定语法

create view 表名 as 虚拟表的查询sql语句

# 具体操作

create view teacher2course as

select * from teacher INNER JOIN course

on teacher.tid = course.teacher_id

;

```

* 注意

```python

"""

1 创建视图在硬盘上只会有表结构 没有表数据(数据还是来自于之前的表)

2 视图一般只用来查询 里面的数据不要继续修改 可能会影响真正的表

"""

```

* 视图到底使用频率高不高呢?

```python

"""

不高

当你创建了很多视图之后 会造成表的不好维护

"""

# 总结

视图了解即可 基本不用!!!

```

### 触发器(了解)

在满足对表数据进行增、删、改的情况下,自动触发的功能

使用触发器可以帮助我们实现监控、日志...

触发器可以在六种情况下自动触发 增前 增后 删前删后 改前改后

#### 基本语法结构

```python

create trigger 触发器的名字 before/after insert/update/delete on 表名

for each row

begin

sql语句

end

# 具体使用 针对触发器的名字 我们通常需要做到见名知意

# 针对增

create trigger tri_before_insert_t1 before insert on t1

for each row

begin

sql语句

end

create trigger tri_after_insert_t1 after insert on t1

for each row

begin

sql语句

end

"""针对删除和修改 书写格式一致"""

ps:修改MySQL默认的语句结束符 只作用于当前窗口

delimiter $$ 将默认的结束符号由;改为$$

delimiter ;

# 案例

CREATE TABLE cmd (

id INT PRIMARY KEY auto_increment,

USER CHAR (32),

priv CHAR (10),

cmd CHAR (64),

sub_time datetime, #提交时间

success enum ('yes', 'no') #0代表执行失败

);

CREATE TABLE errlog (

id INT PRIMARY KEY auto_increment,

err_cmd CHAR (64),

err_time datetime

);

"""

当cmd表中的记录succes字段是no那么就触发触发器的执行去errlog表中插入数据

NEW指代的就是一条条数据对象

"""

delimiter $$

create trigger tri_after_insert_cmd after insert on cmd

for each row

begin

if NEW.success = 'no' then

insert into errlog(err_cmd,err_time) values(NEW.cmd,NEW.sub_time);

end if;

end $$

delimiter ;

# 朝cmd表插入数据

INSERT INTO cmd (

USER,

priv,

cmd,

sub_time,

success

)

VALUES

('jason','0755','ls -l /etc',NOW(),'yes'),

('jason','0755','cat /etc/passwd',NOW(),'no'),

('jason','0755','useradd xxx',NOW(),'no'),

('jason','0755','ps aux',NOW(),'yes');

# 删除触发器

drop trigger tri_after_insert_cmd;

```

### 事务

* 什么是事务

```python

"""

开启一个事务可以包含多条sql语句 这些sql语句要么同时成功

要么一个都别想成功 称之为事务的原子性

"""

```

* 事务的作用

```python

"""

保证了对数据操作的安全性

"""

eg:还钱的例子

egon用银行卡给我的支付宝转账1000

1 将egon银行卡账户的数据减1000块

2 将jason支付宝账户的数据加1000块

你在操作多条数据的时候可能会出现某几条操作不成功的情况

```

* 事务的四大特性

```python

"""

ACID

A:原子性

一个事务是一个不可分割的单位,事务中包含的诸多操作

要么同时成功要么同时失败

C:一致性

事务必须是使数据库从一个一致性的状态变到另外一个一致性的状态

一致性跟原子性是密切相关的

I:隔离性

一个事务的执行不能被其他事务干扰

(即一个事务内部的操作及使用到的数据对并发的其他事务是隔离的,并发执行的事务之间也是互相不干扰的)

D:持久性

也叫"永久性"

一个事务一旦提交成功执行成功 那么它对数据库中数据的修改应该是永久的

接下来的其他操作或者故障不应该对其有任何的影响

"""

```

* 如何使用事务

```python

# 事务相关的关键字

# 1 开启事务

start transaction;

# 2 回滚(回到事务执行之前的状态)

rollback;

# 3 确认(确认之后就无法回滚了)

commit;

"""模拟转账功能"""

create table user(

id int primary key auto_increment,

name char(16),

balance int

);

insert into user(name,balance) values

('jason',1000),

('egon',1000),

('tank',1000);

# 1 先开启事务

start transaction;

# 2 多条sql语句

update user set balance=900 where name='jason';

update user set balance=1010 where name='egon';

update user set balance=1090 where name='tank';

"""

总结

当你想让多条sql语句保持一致性 要么同时成功要么同时失败

你就应该考虑使用事务

"""

```

### 存储过程(了解)

存储过程就类似于python中的自定义函数

它的内部包含了一系列可以执行的sql语句,存储过程存放于MySQL服务端中,你可以直接通过调用存储过程触发内部sql语句的执行

**基本使用**

```python

create procedure 存储过程的名字(形参1,形参2,...)

begin

sql代码

end

# 调用

call 存储过程的名字();

```

#### 三种开发模型

第一种

```python

"""

应用程序:程序员写代码开发

MySQL:提前编写好存储过程,供应用程序调用

好处:开发效率提升了 执行效率也上去了

缺点:考虑到认为元素、跨部门沟通的问题 后续的存储过程的扩展性差

"""

```

第二种

```python

"""

应用程序:程序员写代码开发之外 设计到数据库操作也自己动手写

优点:扩展性很高

缺点:

开发效率降低

编写sql语句太过繁琐 而且后续还需要考虑sql优化的问题

"""

```

第三种

```python

"""

应用程序:只写程序代码 不写sql语句 基于别人写好的操作MySQL的python框架直接调用操作即可ORM框架

优点:开发效率比上面两种情况都要高

缺点:语句的扩展性差 可能会出现效率低下的问题

"""

```

第一种基本不用。一般都是第三种,出现效率问题再动手写sql

* 存储过程具体演示

```python

delimiter $$

create procedure p1(

in m int, # 只进不出 m不能返回出去

in n int,

out res int # 该形参可以返回出去

)

begin

select tname from teacher where tid>m and tid

set res=666; # 将res变量修改 用来标识当前的存储过程代码确实执行了

end $$

delimiter ;

# 针对形参res 不能直接传数据 应该传一个变量名

# 定义变量

set @ret = 10;

# 查看变量对应的值

select @ret;

```

在pymysql模块中如何调用存储过程呢?

```python

import pymysql

conn = pymysql.connect(

host = '127.0.0.1',

port = 3306,

user = 'root',

passwd = '123456',

db = 'day48',

charset = 'utf8',

autocommit = True

)

cursor = conn.cursor(pymysql.cursors.DictCursor)

# 调用存储过程

cursor.callproc('p1',(1,5,10))

"""

@_p1_0=1

@_p1_1=5

@_p1_2=10

"""

# print(cursor.fetchall())

cursor.execute('select @_p1_2;')

print(cursor.fetchall())

```

### 函数

跟存储过程是有区别的,存储过程是自定义函数,函数就类似于是内置函数

```python

('jason','0755','ls -l /etc',NOW(),'yes')

CREATE TABLE blog (

id INT PRIMARY KEY auto_increment,

NAME CHAR (32),

sub_time datetime

);

INSERT INTO blog (NAME, sub_time)

VALUES

('第1篇','2015-03-01 11:31:21'),

('第2篇','2015-03-11 16:31:21'),

('第3篇','2016-07-01 10:21:31'),

('第4篇','2016-07-22 09:23:21'),

('第5篇','2016-07-23 10:11:11'),

('第6篇','2016-07-25 11:21:31'),

('第7篇','2017-03-01 15:33:21'),

('第8篇','2017-03-01 17:32:21'),

('第9篇','2017-03-01 18:31:21');

select date_format(sub_time,'%Y-%m'),count(id) from blog group by date_format(sub_time,'%Y-%m');

```

### 流程控制(了解)

```python

# if判断

delimiter //

CREATE PROCEDURE proc_if ()

BEGIN

declare i int default 0;

if i = 1 THEN

SELECT 1;

ELSEIF i = 2 THEN

SELECT 2;

ELSE

SELECT 7;

END IF;

END //

delimiter ;

# while循环

delimiter //

CREATE PROCEDURE proc_while ()

BEGIN

DECLARE num INT ;

SET num = 0 ;

WHILE num < 10 DO

SELECT

num ;

SET num = num + 1 ;

END WHILE ;

```

### 索引

ps:数据都是存在与硬盘上的,查询数据不可避免的需要进行IO操作

索引:就是一种数据结构,类似于书的目录。意味着以后在查询数据的应该先找目录再找数据,而不是一页一页的翻书,从而提升查询速度降低IO操作

索引在MySQL中也叫“键”,是存储引擎用于快速查找记录的一种数据结构

* primary key

* unique key

* index key

注意foreign key不是用来加速查询用的,不在我们的而研究范围之内

上面的三种key,前面两种除了可以增加查询速度之外各自还具有约束条件,而最后一种index key没有任何的约束条件,只是用来帮助你快速查询数据

**本质**

通过不断的缩小想要的数据范围筛选出最终的结果,同时将随机事件(一页一页的翻)

变成顺序事件(先找目录、找数据)

也就是说有了索引机制,我们可以总是用一种固定的方式查找数据

一张表中可以有多个索引(多个目录)

索引虽然能够帮助你加快查询速度但是也有缺点

```python

"""

1 当表中有大量数据存在的前提下 创建索引速度会很慢

2 在索引创建完毕之后 对表的查询性能会大幅度的提升 但是写的性能也会大幅度的降低

"""

索引不要随意的创建!!!

```

### b+树

```python

"""

只有叶子节点存放的是真实的数据 其他节点存放的是虚拟数据 仅仅是用来指路的

树的层级越高查询数据所需要经历的步骤就越多(树有几层查询数据就需要几步)

一个磁盘块存储是有限制的

为什么建议你将id字段作为索引

占得空间少 一个磁盘块能够存储的数据多

那么久降低了树的高度 从而减少查询次数

"""

```

### 聚集索引(primary key)

```python

"""

聚集索引指的就是主键

Innodb 只有两个文件 直接将主键存放在了idb表中

MyIsam 三个文件 单独将索引存在一个文件

"""

```

### 辅助索引(unique,index)

查询数据的时候不可能一直使用到主键,也有可能会用到name,password等其他字段

那么这个时候你是没有办法利用聚集索引。这个时候你就可以根据情况给其他字段设置辅助索引(也是一个b+树)

```python

"""

叶子节点存放的是数据对应的主键值

先按照辅助索引拿到数据的主键值

之后还是需要去主键的聚集索引里面查询数据

"""

```

### 覆盖索引

在辅助索引的叶子节点就已经拿到了需要的数据

```python

# 给name设置辅助索引

select name from user where name='jason';

# 非覆盖索引

select age from user where name='jason';

```

### 测试索引是否有效的代码

感兴趣就自己试一试 不感兴趣直接忽略

```python

**准备**

​```mysql

#1. 准备表

create table s1(

id int,

name varchar(20),

gender char(6),

email varchar(50)

);

#2. 创建存储过程,实现批量插入记录

delimiter $$ #声明存储过程的结束符号为$$

create procedure auto_insert1()

BEGIN

declare i int default 1;

while(i<3000000)do

insert into s1 values(i,'jason','male',concat('jason',i,'@oldboy'));

set i=i+1;

end while;

END$$ #$$结束

delimiter ; #重新声明分号为结束符号

#3. 查看存储过程

show create procedure auto_insert1\G

#4. 调用存储过程

call auto_insert1();

​```

​``` mysql

# 表没有任何索引的情况下

select * from s1 where id=30000;

# 避免打印带来的时间损耗

select count(id) from s1 where id = 30000;

select count(id) from s1 where id = 1;

# 给id做一个主键

alter table s1 add primary key(id); # 速度很慢

select count(id) from s1 where id = 1; # 速度相较于未建索引之前两者差着数量级

select count(id) from s1 where name = 'jason' # 速度仍然很慢

"""

范围问题

"""

# 并不是加了索引,以后查询的时候按照这个字段速度就一定快

select count(id) from s1 where id > 1; # 速度相较于id = 1慢了很多

select count(id) from s1 where id >1 and id < 3;

select count(id) from s1 where id > 1 and id < 10000;

select count(id) from s1 where id != 3;

alter table s1 drop primary key; # 删除主键 单独再来研究name字段

select count(id) from s1 where name = 'jason'; # 又慢了

create index idx_name on s1(name); # 给s1表的name字段创建索引

select count(id) from s1 where name = 'jason' # 仍然很慢!!!

"""

再来看b+树的原理,数据需要区分度比较高,而我们这张表全是jason,根本无法区分

那这个树其实就建成了“一根棍子”

"""

select count(id) from s1 where name = 'xxx';

# 这个会很快,我就是一根棍,第一个不匹配直接不需要再往下走了

select count(id) from s1 where name like 'xxx';

select count(id) from s1 where name like 'xxx%';

select count(id) from s1 where name like '%xxx'; # 慢 最左匹配特性

# 区分度低的字段不能建索引

drop index idx_name on s1;

# 给id字段建普通的索引

create index idx_id on s1(id);

select count(id) from s1 where id = 3; # 快了

select count(id) from s1 where id*12 = 3; # 慢了 索引的字段一定不要参与计算

drop index idx_id on s1;

select count(id) from s1 where name='jason' and gender = 'male' and id = 3 and email = 'xxx';

# 针对上面这种连续多个and的操作,mysql会从左到右先找区分度比较高的索引字段,先将整体范围降下来再去比较其他条件

create index idx_name on s1(name);

select count(id) from s1 where name='jason' and gender = 'male' and id = 3 and email = 'xxx'; # 并没有加速

drop index idx_name on s1;

# 给name,gender这种区分度不高的字段加上索引并不难加快查询速度

create index idx_id on s1(id);

select count(id) from s1 where name='jason' and gender = 'male' and id = 3 and email = 'xxx'; # 快了 先通过id已经讲数据快速锁定成了一条了

select count(id) from s1 where name='jason' and gender = 'male' and id > 3 and email = 'xxx'; # 慢了 基于id查出来的数据仍然很多,然后还要去比较其他字段

drop index idx_id on s1

create index idx_email on s1(email);

select count(id) from s1 where name='jason' and gender = 'male' and id > 3 and email = 'xxx'; # 快 通过email字段一剑封喉

​```

#### 联合索引

​```mysql

select count(id) from s1 where name='jason' and gender = 'male' and id > 3 and email = 'xxx';

# 如果上述四个字段区分度都很高,那给谁建都能加速查询

# 给email加然而不用email字段

select count(id) from s1 where name='jason' and gender = 'male' and id > 3;

# 给name加然而不用name字段

select count(id) from s1 where gender = 'male' and id > 3;

# 给gender加然而不用gender字段

select count(id) from s1 where id > 3;

# 带来的问题是所有的字段都建了索引然而都没有用到,还需要花费四次建立的时间

create index idx_all on s1(email,name,gender,id); # 最左匹配原则,区分度高的往左放

select count(id) from s1 where name='jason' and gender = 'male' and id > 3 and email = 'xxx'; # 速度变快

​```

慢查询日志

设定一个时间检测所有超出该时间的sql语句,然后针对性的进行优化!

```

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值