当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL进阶

MySQL进阶

2018年08月29日  | 移动技术网IT编程  | 我要评论

索引

1、概述

mysql索引的建立对于mysql的高效运行是很重要的,索引可以大大提高mysql的检索速度。

虽然索引大大提高了查询速度,同时却会降低更新表的速度,如对表进行insert、update和delete。因为更新表时,mysql不仅要保存数据,还要保存一下索引文件。

建立索引会占用磁盘空间的索引文件。

2、索引种类

    • 普通索引:仅加速查询
    • 唯一索引:加速查询 + 列值唯一(可以有null)
    • 主键索引:加速查询 + 列值唯一 + 表中只有一个(不可以有null)
    • 组合索引:多列值组成一个索引,
                    专门用于组合搜索,其效率大于索引合并
    • 全文索引:对文本的内容进行分词,进行搜索 

索引合并:使用多个单列索引组合查询搜索
覆盖索引:select的数据列只用从索引中就能够取得,不必读取数据行,换句话说查询列要被所建的索引覆盖

a、普通索引

普通索引仅有一个功能:加速查询

create table in1(
    nid int not null auto_increment primary key,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text,
    index ix_name (name)
)
创建表+索引
create index index_name on table_name(column_name)
创建索引
drop index_name on table_name;
删除索引
show index from table_name;
查看索引

注意:对于创建索引时如果是blob 和 text 类型,必须指定length。

create index ix_extra on in1(extra(32));

b、唯一索引

唯一索引有两个功能:加速查询 和 唯一约束(可含null)

create table in1(
    nid int not null auto_increment primary key,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text,
    unique ix_name (name)
)
创建唯一索引+表
create unique index 索引名 on 表名(列名)
创建唯一索引
drop unique index 索引名 on 表名
删除唯一索引

c、主键索引

主键有两个功能:加速查询 和 唯一约束(不可含null)

create table in1(
    nid int not null auto_increment primary key,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text,
    index ix_name (name)
)

or

create table in1(
    nid int not null auto_increment,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text,
    primary key(ni1),
    index ix_name (name)
)
创建表+创建主键
alter table 表名 add primary key(列名);
创建主键
alter table 表名 drop primary key;
alter table 表名  modify  列名 int, drop primary key;
删除主键

d、组合索引

组合索引是将n个列组合成一个索引

其应用场景为:频繁的同时使用n列来进行查询,如:where n1 = 'djb' and n2 = 666

create table in3(
    nid int not null auto_increment primary key,
    name varchar(32) not null,
    email varchar(64) not null,
    extra text
)
创建表
create index ix_name_email on in3(name,email);
创建索引

3、相关命令

- 查看表结构
    desc 表名
 
- 查看生成表的sql
    show create table 表名
 
- 查看索引
    show index from  表名
 
- 查看执行时间
    set profiling = 1;
    sql...
    show profiles;

4、使用索引和不使用索引

由于索引是专门用于加速搜索而生,所以加上索引之后,查询效率会快到飞起来。

5、正确使用索引

数据库表中添加索引后确实会让查询速度起飞,但前提必须是正确的使用索引来查询,如果以错误的方式使用,则即使建立索引也会不奏效。
即使建立索引,索引也不会生效:

- like '%xx'
    select * from tb1 where name like '%cn';
- 使用函数
    select * from tb1 where reverse(name) = 'wupeiqi';
- or
    select * from tb1 where nid = 1 or email = 'seven@live.com';
    特别的:当or条件中有未建立索引的列才失效,以下会走索引
            select * from tb1 where nid = 1 or name = 'seven';
            select * from tb1 where nid = 1 or email = 'seven@live.com' and name = 'alex'
- 类型不一致
    如果列是字符串类型,传入条件是必须用引号引起来,不然...
    select * from tb1 where name = 999;
- !=
    select * from tb1 where name != 'alex'
    特别的:如果是主键,则还是会走索引
        select * from tb1 where nid != 123
- >
    select * from tb1 where name > 'alex'
    特别的:如果是主键或索引是整数类型,则还是会走索引
        select * from tb1 where nid > 123
        select * from tb1 where num > 123
- order by
    select email from tb1 order by name desc;
    当根据索引排序时候,选择的映射如果不是索引,则不走索引
    特别的:如果对主键排序,则还是走索引:
        select * from tb1 order by nid desc;
 
- 组合索引最左前缀
    如果组合索引为:(name,email)
    name and email       -- 使用索引
    name                 -- 使用索引
    email                -- 不使用索引

6、其他注意事项

1 - 避免使用select *
2 - count(1)或count(列) 代替 count(*)
3 - 创建表时尽量时 char 代替 varchar
4 - 表的字段顺序固定长度的字段优先
5 - 组合索引代替多个单列索引(经常使用多个条件查询时)
6 - 尽量使用短索引
7 - 使用连接(join)来代替子查询(sub-queries)
8 - 连表时注意条件类型需一致
9 - 索引散列值(重复少)不适合建索引,例:性别不适合

7、limit分页

方案:
记录当前页最大或最小id
1. 页面只有上一页,下一页
# max_id
# min_id
下一页:
select * from userinfo3 where id > max_id limit 10;
上一页:
select * from userinfo3 where id < min_id order by id desc limit 10;
2. 上一页 192 193  [196]  197  198  199 下一页
                    
select * from userinfo3 where id in (select id from (select id from userinfo3 where id > max_id limit 30) as n order by n.id desc limit 10)

8、执行计划

explain + 查询sql - 用于显示sql执行信息参数,根据参考信息可以进行sql优化

mysql> explain select * from tb2;
+----+-------------+-------+------+---------------+------+---------+------+------+-------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-------+
|  1 | simple      | tb2   | all  | null          | null | null    | null |    2 | null  |
+----+-------------+-------+------+---------------+------+---------+------+------+-------+
1 row in set (0.00 sec)

9、慢日志查询

a、配置mysql自动记录慢日志

slow_query_log = off                            是否开启慢日志记录
long_query_time = 2                              时间限制,超过此时间,则记录
slow_query_log_file = /usr/slow.log        日志文件
log_queries_not_using_indexes = off     为使用索引的搜索是否记录

注:查看当前配置信息:
       show variables like '%query%'
     修改当前配置:
    set global 变量名 = 值

b、查看mysql慢日志

mysqldumpslow -s at -a  /usr/local/var/mysql/macbook-pro-3-slow.log

"""
--verbose    版本
--debug      调试
--help       帮助
 
-v           版本
-d           调试模式
-s order     排序方式
             what to sort by (al, at, ar, c, l, r, t), 'at' is default
              al: average lock time
              ar: average rows sent
              at: average query time
               c: count
               l: lock time
               r: rows sent
               t: query time
-r           反转顺序,默认文件倒序拍。reverse the sort order (largest last instead of first)
-t num       显示前n条just show the top n queries
-a           不要将sql中数字转换成n,字符串转换成s。don't abstract all numbers to n and strings to 's'
-n num       abstract numbers with at least n digits within names
-g pattern   正则匹配;grep: only consider stmts that include this string
-h hostname  mysql机器名或者ip;hostname of db server for *-slow.log filename (can be wildcard),
             default is '*', i.e. match all
-i name      name of server instance (if using mysql.server startup script)
-l           总时间中不减去锁定时间;don't subtract lock time from total time
"""
view

事务

1、概述

mysql 事务主要用于处理操作量大,复杂度高的数据。比如说,在人员管理系统中,你删除一个人员,你即需要删除人员的基本资料,也要删除和该人员相关的信息,如信箱,文章等等,这样,这些数据库操作语句就构成一个事务,但是一旦有某一个出现错误,即可回滚到原来的状态,从而保证数据库数据完整性。!

  • 在mysql中只有使用了innodb数据库引擎的数据库或表才支持事务
  • 事务处理可以用来维护数据库的完整性,保证成批的sql语句要么全部执行,要么全部不执行
  • 事务用来管理insert,update,delete语句

一般来说,事务是必须满足4个条件(acid): atomicity(原子性)、consistency(稳定性)、isolation(隔离性)、durability(可靠性)

  • 1、事务的原子性:一组事务,要么成功;要么撤回。
  • 2、稳定性 : 有非法数据(外键约束之类),事务撤回。
  • 3、隔离性:事务独立运行。一个事务处理后的结果,影响了其他事务,那么其他事务会撤回。事务的100%隔离,需要牺牲速度。
  • 4、可靠性:软、硬件崩溃后,innodb数据表驱动会利用日志文件重构修改。可靠性和高速度不可兼得, innodb_flush_log_at_trx_commit选项 决定什么时候吧事务保存到日志里。

2、事务操作

  • 开启事务 start transaction
  • 回滚事务 rollback
  • 提交事务 commit
  • 保留点    savepoint
delimiter \\      -- 此条可更改sql语句结束符
create procedure p1(
    out p_return_code tinyint
)
begin 
  declare exit handler for sqlexception 
  begin 
    -- error 
    set p_return_code = 1; 
    rollback; 
  end; 
 
  declare exit handler for sqlwarning 
  begin 
    -- warning 
    set p_return_code = 2; 
    rollback; 
  end; 
 
  start transaction; 
    delete from tb1;
    insert into tb2(name)values('seven');
  commit; 
 
  -- success 
  set p_return_code = 0; 
 
  end\\
delimiter ;

视图

视图是一个虚拟表(非真实存在),其本质是【根据sql语句获取动态的数据集,并为其命名】,用户使用时只需使用【名称】即可获取结果集,并可以将其当作表来使用。

select
    *
from
    (
        select
            nid,
            name
        from
            tb1
        where
            nid > 2
    ) as a
where
    a. name > 'djb';
临时表搜素

1、创建视图

--格式:create view 视图名称 as  sql语句
create view v1 as 
selet nid, 
    name
from
    a
where
    nid > 4
创建视图

2、删除视图

--格式:drop view 视图名称

drop view v1
删除视图

3、修改视图

-- 格式:alter view 视图名称 as sql语句

alter view v1 as
selet a.nid,
    b. name
from
    a
left join b on a.id = b.nid
left join c on a.id = c.nid
where
    a.id > 2
and c.nid < 5
修改视图

4、使用视图

使用视图时,将其当作表进行操作即可,由于视图是虚拟表,所以无法使用其对真实表进行创建、更新和删除操作,仅能做查询用。

select * from v1
view code

触发器

对某个表进行【增/删/改】操作的前后如果希望触发某个特定的行为时,可以使用触发器,触发器用于定制用户对表的行进行【增/删/改】前后的行为。

1、创建基本语法

# 插入前
create trigger tri_before_insert_tb1 before insert on tb1 for each row
begin
    ...
end

# 插入后
create trigger tri_after_insert_tb1 after insert on tb1 for each row
begin
    ...
end

# 删除前
create trigger tri_before_delete_tb1 before delete on tb1 for each row
begin
    ...
end

# 删除后
create trigger tri_after_delete_tb1 after delete on tb1 for each row
begin
    ...
end

# 更新前
create trigger tri_before_update_tb1 before update on tb1 for each row
begin
    ...
end

# 更新后
create trigger tri_after_update_tb1 after update on tb1 for each row
begin
    ...
end
view code
delimiter //
create trigger tri_before_insert_tb1 before insert on tb1 for each row
begin

if new. name == 'alex' then
    insert into tb2 (name)
values
    ('aa')
end
end//
delimiter ;
插入前触发器
delimiter //
create trigger tri_after_insert_tb1 after insert on tb1 for each row
begin
    if new. num = 666 then
        insert into tb2 (name)
        values
            ('666'),
            ('666') ;
    elseif new. num = 555 then
        insert into tb2 (name)
        values
            ('555'),
            ('555') ;
    end if;
end//
delimiter ;
插入后触发器

特别的:new表示即将插入的数据行,old表示即将删除的数据行。

2、删除触发器

drop trigger tri_after_insert_tb1;
view code

3、使用触发器

触发器无法由用户直接调用,而知由于对表的【增/删/改】操作被动引发的。

insert into tb1(num) values(666)
view code

存储过程

存储过程是一个sql语句集合,当主动去调用存储过程时,其中内部的sql语句会按照逻辑执行。

1、创建存储过程

-- 创建存储过程

delimiter //
create procedure p1()
begin
    select * from t1;
end//
delimiter ;



-- 执行存储过程

call p1()
view code

对于存储过程,可以接收参数,其参数有三类:

  • in          仅用于传入参数用
  • out        仅用于返回值用
  • inout     既可以传入又可以当作返回值
delimiter \\
create procedure p1(
    in i1 int,
    in i2 int,
    inout i3 int,
    out r1 int
)
begin
    declare temp1 int;
    declare temp2 int default 0;
    
    set temp1 = 1;

    set r1 = i1 + i2 + temp1 + temp2;
    
    set i3 = i3 + 100;

end\\
delimiter ;

-- 执行存储过程
set @t1 =4;
set @t2 = 0;
call p1 (1, 2 ,@t1, @t2);
select @t1,@t2;
有参数的储存过程
 delimiter //
 create procedure p1()
 begin
     select * from v1;
 end //
 delimiter ;
结果集
delimiter //
                    create procedure p2(
                        in n1 int,
                        inout n3 int,
                        out n2 int,
                    )
                    begin
                        declare temp1 int ;
                        declare temp2 int default 0;

                        select * from v1;
                        set n2 = n1 + 100;
                        set n3 = n3 + n1 + 100;
                    end //
                    delimiter ;
结果集+out值

2、删除存储过程

drop procedure proc_name;
view code

3、执行存储过程

-- 无参数
call proc_name()

-- 有参数,全in
call proc_name(1,2)

-- 有参数,有in,out,inout
set @t1=0;
set @t2=3;
call proc_name(1,2,@t1,@t2)
执行储存过程
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
cursor = conn.cursor(cursor=pymysql.cursors.dictcursor)
# 执行存储过程
cursor.callproc('p1', args=(1, 22, 3, 4))
# 获取执行完存储的参数
cursor.execute("select @_p1_0,@_p1_1,@_p1_2,@_p1_3")
result = cursor.fetchall()

conn.commit()
cursor.close()
conn.close()


print(result)
pymysql执行储存过程

函数

mysql中提供了许多内置函数,例如:

char_length(str)
        返回值为字符串str 的长度,长度的单位为字符。一个多字节字符算作一个单字符。
        对于一个包含五个二字节字符集, length()返回值为 10, 而char_length()的返回值为5。

    concat(str1,str2,...)
        字符串拼接
        如有任何一个参数为null ,则返回值为 null。
    concat_ws(separator,str1,str2,...)
        字符串拼接(自定义连接符)
        concat_ws()不会忽略任何空字符串。 (然而会忽略所有的 null)。

    conv(n,from_base,to_base)
        进制转换
        例如:
            select conv('a',16,2); 表示将 a 由16进制转换为2进制字符串表示

    format(x,d)
        将数字x 的格式写为'#,###,###.##',以四舍五入的方式保留小数点后 d 位, 并将结果以字符串的形式返回。若  d 为 0, 则返回结果不带有小数点,或不含小数部分。
        例如:
            select format(12332.1,4); 结果为: '12,332.1000'
    insert(str,pos,len,newstr)
        在str的指定位置插入字符串
            pos:要替换位置其实位置
            len:替换的长度
            newstr:新字符串
        特别的:
            如果pos超过原字符串长度,则返回原字符串
            如果len超过原字符串长度,则由新字符串完全替换
    instr(str,substr)
        返回字符串 str 中子字符串的第一个出现位置。

    left(str,len)
        返回字符串str 从开始的len位置的子序列字符。

    lower(str)
        变小写

    upper(str)
        变大写

    ltrim(str)
        返回字符串 str ,其引导空格字符被删除。
    rtrim(str)
        返回字符串 str ,结尾空格字符被删去。
    substring(str,pos,len)
        获取字符串子序列

    locate(substr,str,pos)
        获取子序列索引位置

    repeat(str,count)
        返回一个由重复的字符串str 组成的字符串,字符串str的数目等于count 。
        若 count <= 0,则返回一个空字符串。
        若str 或 count 为 null,则返回 null 。
    replace(str,from_str,to_str)
        返回字符串str 以及所有被字符串to_str替代的字符串from_str 。
    reverse(str)
        返回字符串 str ,顺序和字符顺序相反。
    right(str,len)
        从字符串str 开始,返回从后边开始len个字符组成的子序列

    space(n)
        返回一个由n空格组成的字符串。

    substring(str,pos) , substring(str from pos) substring(str,pos,len) , substring(str from pos for len)
        不带有len 参数的格式从字符串str返回一个子字符串,起始于位置 pos。带有len参数的格式从字符串str返回一个长度同len字符相同的子字符串,起始于位置 pos。 使用 from的格式为标准 sql 语法。也可能对pos使用一个负值。假若这样,则子字符串的位置起始于字符串结尾的pos 字符,而不是字符串的开头位置。在以下格式的函数中可以对pos 使用一个负值。

        mysql> select substring('quadratically',5);
            -> 'ratically'

        mysql> select substring('foobarbar' from 4);
            -> 'barbar'

        mysql> select substring('quadratically',5,6);
            -> 'ratica'

        mysql> select substring('sakila', -3);
            -> 'ila'

        mysql> select substring('sakila', -5, 3);
            -> 'aki'

        mysql> select substring('sakila' from -4 for 2);
            -> 'ki'

    trim([{both | leading | trailing} [remstr] from] str) trim(remstr from] str)
        返回字符串 str , 其中所有remstr 前缀和/或后缀都已被删除。若分类符both、leadin或trailing中没有一个是给定的,则假设为both 。 remstr 为可选项,在未指定情况下,可删除空格。

        mysql> select trim('  bar   ');
                -> 'bar'

        mysql> select trim(leading 'x' from 'xxxbarxxx');
                -> 'barxxx'

        mysql> select trim(both 'x' from 'xxxbarxxx');
                -> 'bar'

        mysql> select trim(trailing 'xyz' from 'barxxyz');
                -> 'barx'

部分内置函数
部分内置函数

1、自定义函数

delimiter \\
create function f1(
    i1 int,
    i2 int)
returns int
begin
    declare num int;
    set num = i1 + i2;
    return(num);
end \\
delimiter ;
view code

2、删除函数

drop function func_name;
view code

3、执行函数

# 获取返回值
declare @i varchar(32);
select upper('djb') into @i;
select @i;


# 在查询中使用
select f1(11,nid) ,name from tb2;
view code

其它

1、条件语句

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 ;
if条件语句

2、循环语句

delimiter \\
create procedure proc_while ()
begin

    declare num int ;
    set num = 0 ;
    while num < 10 do
        select
            num ;
        set num = num + 1 ;
    end while ;

end\\
delimiter ;
while循环
delimiter \\
create procedure proc_repeat ()
begin

    declare i int ;
    set i = 0 ;
    repeat
        select i;
        set i = i + 1;
        until i >= 5
    end repeat;

end\\
delimiter ;
repeat循环
begin
    
    declare i int default 0;
    loop_label: loop
        
        set i=i+1;
        if i<8 then
            iterate loop_label;
        end if;
        if i>=10 then
            leave loop_label;
        end if;
        select i;
    end loop loop_label;

end
loop

3、动态执行sql语句

delimiter \\
drop procedure if exists proc_sql \\
create procedure proc_sql ()
begin
    declare p1 int;
    set p1 = 11;
    set @p1 = p1;

    prepare prod from 'select * from tb2 where nid > ?';
    execute prod using @p1;
    deallocate prepare prod; 

end\\
delimiter ;
view code

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网