MySQL

mySQL:

    数据库操作:

        1.显示数据库

            show databases;

        2.创建数据库

            create database mihon_test default charset utf8 collate utf8_general_ci;

        3.使用数据库

            use mihon_test;

        4.用户管理

            1.创建用户

                create user 'mihon'@'127.0.0.1' indentified by '123';

            2.删除用户

                drop user 'mihon'@'172.0.0.1';

            3.修改用户

                rename user 'mihon'@'172.0.0.1'; to 'mihon.zhong'@'127.0.0.1';

            4.修改密码

                set passwd for 'mihon'@'127.0.0.1' = Password('1234')

        5.权限管理

            1.查看权限

                show grants for 'mihon'@'127.0.0.1';

            2.授权

                grant 权限 on mihon_test.score to 'mihon'@'127.0.0.1'

            3.取消权限

                revoke 权限 on mihon_test.score from 'mihon'@'127.0.0.1'

               

    数据库表操作

        1.创建表

            create table score(

                sid int not null auto_incrememt primary key,

                student_id int not null,

                course_id int not null default 0,

                constraint fk_ss foreign key (student_id) references student(sid),

                constraint fk_cc forwign key (course_id) references course(cid)

                )engine=innodb default charset=utf8;

        2.删除表

            drop table student;

        3.修改表

            1.添加列

                alter table student add city int null;

            2.删除列

                alter table student drop column city;

            3.修改列

                .alter table student modify column name varchar(64) not null;

                .alter table student change name city varchar not null;

            4.删除主键

                .alter table student drop primary key(sid)

                .alter table student modify sid,drop primary key;

            5.添加外键

                alter table score add constraint kc_cc foreign key score(course_id) references course(sid);

            6.删除外键

                alter table score drop foreign key fk_cc;

            7.修改默认值

                alter table score alter number set default 0;

            8.删除默认值

                alter table course alter number drop default;

            9.插入数据

                .insert into student (name) values ('mihon'),('allon');

                .insert into student (name) select (student_name) from score;

            10.删除数据

                delete from student;

                delete from student where sid=10;

            11.查

                select * from student where id>10 and name='mihon';

            12.条件

                select * from student where sid between 2 and 5;

                select * form student where sid in(11,22,33);

                select * form student where sid not in(11,22,33);

                select * from student where sid in(select sid from score);

            13.通配符

                select * from student where name='mih%';

                select * from student where name='miho.';

            14.限制

                select * from student limit 5; 前5行

                select * from student limit4,5; 从第4行开始的5行

                select * from student limit 5 offset 4; 从第4行开始的5行

            15.排序

                select * from student order by sid asc --升序

                select * form student order by sid desc --降序

                select * form student order by sid asc ,name desc; 根据sid升序,name 降序

            16.分组

                select * from student group by name;

                select * from student where sid>1 group by name order by sid desc;

            17.连表

                inner join 无对应关系则不显示

                left join A表所有显示

                right join B表所有显示

            18.组合

                select nickname from A union select name from B; --自动处理重合

                select nickname from A union all select name from B; --组合,不处理重合   

    索引:是数据库专门用于帮助用户快速查询数据的一种结构

       

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

            1.创建表+索引:index index_name (name)

            2.表外创建索引:create index index_name on table_name(column_name)

            3.删除索引:drop index_name on table_name

            4.查看索引:show index from table_name

       

        唯一索引:有两个功能,加速查询,唯一约束

            1.创建表+索引:unique index_name (name)

            2.表外创建索引: create unique index_name on table_name(column_name)

            3.删除索引:drop unique from table_name

       

        主键索引:加快查询,唯一约束(不能含null)

            1.创建表+索引:nid int not null auto_incrememt primary key,

            2.表外创建索引:alter table table_name add primary key(column_name)

            3.删除索引:alter table table_name drop primary key

                        alter table table_name modify column_name int, drop primary key

           

        组合索引:是将N个列组合成一个索引

            1.应用场景,频繁使用N列来进行查询,如 where name='alex' and nid=12

            2.表外创建索引:create index_name_email on table_name(name,emal)

            3.创建表+索引:index index_name_email (name,emal)

            3.删除索引: drop index_name on table_name

            4.其他:对于同时搜索N个条件时,组合索引的性能好于多个单一索引合并

                .name and emal  --使用索引

                .name           --使用索引

                .emal           --不使用索引

           

    正确命中索引:

        1.无法命中索引:

            1.左边模糊匹配

                select * from student where name='%ex'

            2.使用内置函数

                select * from student reverse(name)='mihon'

            3.or条件中有未建立索引的列

                select * from student where sid=12 or name='mihon'(name为建立索引)

            4.类型不一致(如果是字符串类型,必须用引号引起来)

                select * form student where name=999

            5.!=(如果是主键还是会走索引)

                select * from student where sid!=12

            6.>(如果是主键还是会走索引)

                select * form student where sid>12

            7.order by(当根据索引排序时候,如果映射的不是索引,不走索引,除主键外)

                select emal from student order by name desc;

            8.组合索引最左前缀

                select * from student where emal='mihon@162.com'

           

        2.注意事项

            1.避免使用 select *

            2.count(1)或者count(column_name)替代count(*)

            3.创建表是尽量使用定长(char)代替变长(varchar)

            4.表的字段顺序固定长度的字段优先

            5.组合索引代替多个单列索引(经常使用多个条件查询时)、

            6.尽量使用短索引

            7.使用(join)来代替子查询(sub-queries)

            8.连表时注意条件类型一致

            9.索引散列值(重复少)不适合建立索引(如性别)

           

    执行计划:

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

        1.select_type

            simple      简单查询

            primary     最外层查询

            subquery    映射为子查询

            derived     子查询

            union       联合

            union result 使用联合的结果

        2.type

            1.ALL    全表扫描,对于数据从表头到尾找一遍(有limit限制,则找到之后就不在继续向下扫描)

            2.INDEX  全表扫描(select name from student)

            3.RANGE  对索引进行范围查找(select name from student where sid between 2 and 4)(in < )

            4.INDEX_MERGE  合并索引,使用多个单列索引

            5.REF    根据所以查找一个或多个值(select name form student where name like "mih%")

            6.EQ_REF 连接时使用主键primary key 或者 联合 unique

            7.CONST  常数 只有一个匹配行,在这行的值可被优化器剩余部分认为时常数

                (select sid from student sid=2)

            8.SYSTEM 系统,这是const连接类型的一个特列

           

        3.possible_keys

            可能使用的索引

        4.key

            真实使用的

        5.key_len

            查询中使用索引字节changd

        6.rows

            估计为了找到所需的行热要读取的行数 --预估

       

    视图:

        视图是一个虚拟表,方便用户简化SQL语句,视图不能进行对数据的更改操作

        1.创建视图:create view v1 as select * from student

        2.删除视图:drop view v1

        3.修改视图:alter view v1 as select * from student where sid>10

        4.使用视图:select * from v1

   

    存储过程:

        存储过程是一个SQL语句集合

        1.无参存储过程

            delimiter //

            create procedure p1()

            begin

                select * from student;

            end//

            delimiter ;

        2.有参存储过程

            1.in    仅用于传入参数

            2.out   仅用于返回值

            3.inout 既可以传入参数又可以返回值

        3.删除存储过程

            drop procedure proc_name

        4.执行存储过程

            1.无参 call proc_name()

            2.有参

                set @t1=0;set @t2=2;

                call proc_name(1,2,@t1,@t2)

        5.pymysql执行存储过程

            import pymaysql

            conn = pymaysql.connect(host='127.0.0.1',port=3306,user='root',passwd='123',db='mihon_test')

            cursor = conn.cursor(cursor=pymaysql.cursor.DictCursor)

            #执行存储过程

            cursor.callproc('p1',args=(1,22,3,4))

            #获取存储参数

            cursor.execute("select @_p0,@_p1,@_p2,@_p3")

            result = cursor.fetchall()

            conn.commit()

            cursor.close()

            conn.close()

        6.执行动态mySQL

            delimiter \

            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 ;

               

    事物:

        事务用于将某些操作的多个SQL作为原子性操作,一旦有某一个出现错误,

        即可以回滚到原来的状态,从而保证数据库数据的完整性

           

    触发器:

        对某个表进行(增,删,改)操作的前后触发摸个特定的行为。

        1.创建触发器:[new.name,old.name(new表示即将插入的数据行,old表示即将删除的数据行)]

            delimiter //

            create triggre tri_after_insert_student after insert on student for each row

            begin

                if new.name = 'mihon' then

                    insert into score (number) values (60,70)

                elseif new.name = 'sin' then

                    insert into score (number) values (50,40)

                endif

            end//

            delimiter ;

        2.删除触发器:

            drop triggre tri_after_insert_student;

        3.使用触发器;

            insert into student (name)values('mihon')

       

    pymySQL:

        import pymysql

        #创建连接

        conn = pymysql.connect(host='127.0.0.1',post=3306,passwd='123',db='mihon_test')

        #创建游标

        cursor = conn.cursor()

        #执行SQL,并返回受影响的行数

        effect_row = cursor.execute('select * from student where sid=%s',(1,))

        #提交,保存新建或者修改的数据

        conn.commit()

        #关闭游标

        cursor.close()

        #关闭连接

        conn.close()

        #获取最新自增ID

        new_id = cursor.lastrowid

        #多条插入

        cursor.executemany('insert into student (name) values ("mihon"),("allon")')

        #获取第一行数据

        row_1 = cursor.fetchone()

        #获取前n行数据

        row_2 = cursor.fetchmany(3)

        #获取所有数据

        row_3 = cursor.fetchall()

        #移动游标获取数据

            .cursor.scroll(1,mode='relative') #相对于当前位置移动1个

            .cursor.scroll(2,mode='absolute') #相对于绝对位置移动2个,意思就是取第二个

        #默认获取的数据类型是元祖类型,

        cursor = conn.cursor(cursor=pymaysql.cursor.DictCursor)

原文地址:https://www.cnblogs.com/mihon/p/8980796.html