Mysql (二)

一. PyMysql

链接地址

二. 事务

a.数据库开启事务命令  

#start transaction 开启事务
#Rollback 回滚事务,即撤销指定的sql语句(只能回退insert delete update语句),回滚到上一次commit的位置
#Commit 提交事务,提交未存储的事务
#savepoint 保留点 ,事务处理中设置的临时占位符 你可以对它发布回退(与整个事务回退不同)
create table account(
    id int,
    name varchar(32),
    balance double);

insert into account values(1,"alex",8000);
insert into account values(2,"egon",2000);



#方式一: 更改数据后回滚,数据回到原来

select * from account;
    +------+------+---------+
    | id   | name | balance |
    +------+------+---------+
    |    1 | alex |    8000 |
    |    2 | egon |    2000 |
    +------+------+---------+

start transaction;      #开启事务后,更改数据发现数据变化

update account set balance=balance-1000 where id=1;   #alex减去1000
select * from account;
    +------+------+---------+
    | id   | name | balance |
    +------+------+---------+
    |    1 | alex |    7000 |
    |    2 | egon |    2000 |
    +------+------+---------+


rollback;               #回滚后,发现数据回到原来

select * from account;
    +------+------+---------+
    | id   | name | balance |
    +------+------+---------+
    |    1 | alex |    8000 |
    |    1 | egon |    2000 |
    +------+------+---------+


#方式二: 更改数据后提交

select * from account;
    +------+------+---------+
    | id   | name | balance |
    +------+------+---------+
    |    1 | alex |    8000 |
    |    2 | egon |    2000 |
    +------+------+---------+

update account set balance=balance-1000 where id=1;
pdate account set balance=balance+1000 where id=2;
Commit;

 select * from account;
    +------+------+---------+
    | id   | name | balance |
    +------+------+---------+
    |    1 | alex |    7000 |
    |    2 | egon |    3000 |
    +------+------+---------+
数据库 事务操作演示
import pymysql

#添加数据

conn = pymysql.connect(host='10.37.129.3', port=3306, user='egon', passwd='123456', db='wuSir',charset="utf8")

cursor = conn.cursor()


try:
    insertSQL0="INSERT INTO account (name,balance) VALUES ('oldboy',4000)"
    insertSQL1="UPDATE account set balance=balance-1000 WHERE id=1"
    insertSQL2="UPDATE account set balance=balance+1000 WHERE id=2"

    cursor = conn.cursor()

    cursor.execute(insertSQL0)
    conn.commit()                   


    #主动触发Exception,事务回滚,回滚到上面conn.commit() 
    cursor.execute(insertSQL1)
    raise Exception
    cursor.execute(insertSQL2)
    cursor.close()
    conn.commit()

except Exception as e:

    conn.rollback()
    conn.commit()


cursor.close()
conn.close()
python中调用数据库启动事务

三. 视图 

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

a. 创建视图

#格式:CREATE VIEW 视图名称 AS  SQL语句
 
#演示
create view v1 as select * from student where sid > 10;

#下次调用
select * from v1;

b. 删除视图

#格式:DROP VIEW 视图名称

#演示
drop view v1;

c. 修改视图

#格式:ALTER VIEW 视图名称 AS SQL语句

#演示
alter view v1 as select * from student where sid > 13;

四. 触发器

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

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

a. 创建基本语法

# 插入前
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 t2 before insert on student for each row
BEGIN
insert into teacher(tname) values("张三");
END //
delimiter ;


#student插入数据,查看teacher表中是否有数据

insert into student(gender,class_id,sname) values("",3,"王五");


#删除触发器

drop trigger t2;



#----------------------示例二

#重新创建  new   

delimiter //
create trigger t2 before insert on student for each row
BEGIN
insert into teacher(tname) values(NEW.sname);
END //
delimiter ;

#创建的触发的name 相同
insert into student(gender,class_id,sname) values("",3,"李五");
触发器 演示

五. 函数 

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'
部分内置函数

  官方内置函数 

a. 显示时间月份

select DATE_FORMAT(ctime, "%Y-%m"),count(1) from blog group DATE_FORMAT(ctime, "%Y-%m")

2019-11   2
2019-10   2

b. 自定义函数

#自定义函数

delimiter //
create function f1(
    i1 int,
    i2 int)
returns int
BEGIN
    declare num int;
    set num = i1 + i2;
    return(num);
END //
delimiter ;


#执行函数

select f1(1,99);
+----------+
| f1(1,99) |
+----------+
|      100 |
+----------+
View Code

c. 删除函数

#drop function func_name;

d. 执行函数

# 获取返回值
declare @i VARCHAR(32);
select UPPER('alex') into @i;
SELECT @i;


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

六. 存储过程

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

a. 创建存储过程

#定义存储过程

delimiter //
create procedure p1()
BEGIN
  select * from student;
  insert into teacher(tname) values("alex");
END //
delimiter ;



#调用

call p1();
无参数存储过程 演示
import pymysql


conn = pymysql.connect(host='10.37.129.3', port=3306, user='egon', passwd='123456', db='wuSir',charset="utf8")

cursor = conn.cursor()

cursor.callproc("p1")

conn.commit()

result = cursor.fetchall()
print(result)


cursor.close()
conn.close()
pymysql 调用存储过程

b. 有参数存储过程

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

  • in          仅用于传入参数用
  • out        仅用于返回值用
  • inout     既可以传入又可以当作返回值
delimiter //
create procedure p3(
    in n1 int,
    out n2 int
)
BEGIN
    set n2 = 123;
    select * from student where sid > n1;
END //
delimiter ;


set @v1= 0;
select @v1;

#调用 发现@v1的值发生变化
call p3(12,@v1);
select @v1;
有参数存储过程演示
#----------mysql 代码

delimiter //
create procedure p4(
    in n1 int,
    out n2 int
)
BEGIN
    set n2 = 123;
    select * from student where sid > n1;
END //
delimiter ;

set @_p3_0 = 12;
set @_p3_1 = 2;


#调用 发现@v1的值发生变化
call p3(@_p3_0,@_p3_1);

select @_p3_0;
select @_p3_1;



#--------pymysql--------

import pymysql


conn = pymysql.connect(host='10.37.129.3', port=3306, user='egon', passwd='123456', db='wuSir',charset="utf8")
cursor = conn.cursor()


#获取结果集
cursor.callproc("p3",(13,2))     #相当于mysql set定义的两个变量和call执行


#找出in out 的参数值

cursor.execute("select @_p3_0,@_p3_1")
r2 = cursor.fetchall()
print(r2)


cursor.close()
conn.close()
pymysql 操作有参数的存储过程

c. 事务

delimiter \
                        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 ;
事务 演示

d. 游标

#  创建A,B表  把A表数据插入B表

create table A(
    id int,
    num int
    )engine=innodb default charset=utf8;

create table B(
    id int not null auto_increment primary key,
    num int
    )engine=innodb default charset=utf8;

insert into A(id,num) values(1,100),(2,200),(3,300);



# 创建游标

delimiter //
create procedure p9()
begin
    declare row_id int;
    declare row_num int;
    declare done INT DEFAULT FALSE;
    declare temp int;

    declare my_cursor CURSOR FOR select id,num from A;
    declare CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    open my_cursor;
        xxoo: LOOP
            fetch my_cursor into row_id,row_num;
            if done then
                leave xxoo;
            END IF;
            set temp = row_id + row_num;
            insert into B(num) values(temp);
        end loop xxoo;
    close my_cursor;

end  //
delimiter ;



#执行 检查

call p9();
select * from B;
游标 案例演示

e. 动态执行SQL 

delimiter \
    CREATE PROCEDURE p8 (
        in nid int
    )
    BEGIN
        set @nid = nid;
        PREPARE prod FROM 'select * from student where sid > ?';
        EXECUTE prod USING @nid;
        DEALLOCATE prepare prod; 
    END\
    delimiter ;
View Code

七. 索引

MySQL中常见索引有: 

  • 普通索引:  加速查询
  • 唯一索引:      加速查询 + 列值唯一  + (可以有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);

#注意:对于创建索引时如果是BLOB 和 TEXT 类型,必须指定length。
create index ix_extra on in1(extra(32));


#删除索引
drop index_name on table_name;

#查看索引
show index from table_name;
普通索引 演示

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
)

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


#追加主键
alter table 表名 add primary key(列名);

#删除主键
alter table 表名 drop primary key;
alter table 表名  modify  列名 int, drop primary key;
主键 演示

d. 组合索引

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

其应用场景为:频繁的同时使用n列来进行查询,如:where n1 = 'alex' 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);



#-----------------
#如上创建组合索引之后,查询:

name and email  -- 使用索引
name                 -- 使用索引
email                 -- 不使用索引
#注意:对于同时搜索n个条件时,组合索引的性能好于多个单一索引合并。
组合索引 演示

八. 分页 

    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
        )
分页方案

九. 执行计划

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)
id
        查询顺序标识
            如:mysql> explain select * from (select nid,name from tb1 where nid < 10) as B;
            +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+
            | id | select_type | table      | type  | possible_keys | key     | key_len | ref  | rows | Extra       |
            +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+
            |  1 | PRIMARY     | <derived2> | ALL   | NULL          | NULL    | NULL    | NULL |    9 | NULL        |
            |  2 | DERIVED     | tb1        | range | PRIMARY       | PRIMARY | 8       | NULL |    9 | Using where |
            +----+-------------+------------+-------+---------------+---------+---------+------+------+-------------+
        特别的:如果使用union连接气值可能为null


    select_type
        查询类型
            SIMPLE          简单查询
            PRIMARY         最外层查询
            SUBQUERY        映射为子查询
            DERIVED         子查询
            UNION           联合
            UNION RESULT    使用联合的结果
            ...
    table
        正在访问的表名


    type
        查询时的访问方式,性能:all < index < range < index_merge < ref_or_null < ref < eq_ref < system/const
            ALL             全表扫描,对于数据表从头到尾找一遍
                            select * from tb1;
                            特别的:如果有limit限制,则找到之后就不在继续向下扫描
                                   select * from tb1 where email = 'seven@live.com'
                                   select * from tb1 where email = 'seven@live.com' limit 1;
                                   虽然上述两个语句都会进行全表扫描,第二句使用了limit,则找到一个后就不再继续扫描。

            INDEX           全索引扫描,对索引从头到尾找一遍
                            select nid from tb1;

            RANGE          对索引列进行范围查找
                            select *  from tb1 where name < 'alex';
                            PS:
                                between and
                                in
                                >   >=  <   <=  操作
                                注意:!= 和 > 符号


            INDEX_MERGE     合并索引,使用多个单列索引搜索
                            select *  from tb1 where name = 'alex' or nid in (11,22,33);

            REF             根据索引查找一个或多个值
                            select *  from tb1 where name = 'seven';

            EQ_REF          连接时使用primary key 或 unique类型
                            select tb2.nid,tb1.name from tb2 left join tb1 on tb2.nid = tb1.nid;



            CONST           常量
                            表最多有一个匹配行,因为仅有一行,在这行的列值可被优化器剩余部分认为是常数,const表很快,因为它们只读取一次。
                            select nid from tb1 where nid = 2 ;

            SYSTEM          系统
                            表仅有一行(=系统表)。这是const联接类型的一个特例。
                            select * from (select nid from tb1 where nid = 1) as A;
    possible_keys
        可能使用的索引

    key
        真实使用的

    key_len
        MySQL中使用索引字节长度

    rows
        mysql估计为了找到所需的行而要读取的行数 ------ 只是预估值

    extra
        该列包含MySQL解决查询的详细信息
        “Using index”
            此值表示mysql将使用覆盖索引,以避免访问表。不要把覆盖索引和index访问类型弄混了。
        “Using where”
            这意味着mysql服务器将在存储引擎检索行后再进行过滤,许多where条件里涉及索引中的列,当(并且如果)它读取索引时,就能被存储引擎检验,因此不是所有带where子句的查询都会显示“Using where”。有时“Using where”的出现就是一个暗示:查询可受益于不同的索引。
        “Using temporary”
            这意味着mysql在对查询结果排序时会使用一个临时表。
        “Using filesort”
            这意味着mysql会对结果使用一个外部索引排序,而不是按索引次序从表里读取行。mysql有两种文件排序算法,这两种排序方式都可以在内存或者磁盘上完成,explain不会告诉你mysql将使用哪一种文件排序,也不会告诉你排序会在内存里还是磁盘上完成。
        “Range checked for each record(index map: N)”
            这个意味着没有好用的索引,新的索引将在联接的每一行上重新估算,N是显示在possible_keys列中索引的位图,并且是冗余的。
View Code

十. 其它注意事项

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

十一. 下列不走索引

- 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                -- 不使用索引

  

 

  

 

 wuSir   wuSir

原文地址:https://www.cnblogs.com/golangav/p/6972888.html