windows,pycharm,python,PyMySQL( 六 )


insert into sc (student_id,course_id,number)selectsid,2,(select max(num)fromscorewherecourse_id=3) as numfromstudentwheresid not in (selectstudent_idfromscorewherecourse_id=2)
7.示例2: 博客系统与索引 7.1 表结构
7.2索引
常见索引:
1,主键索引:加速查找,不能为空,不能重复,(多列) 联合主键索引
【windows,pycharm,python,PyMySQL】create table 表名(id int not null auto_increment,name varchar(32) not null,primary key(id)--主键索引);create table 表名(id int not null auto_increment,name varchar(32) not null,primary key(id,name)--多列,联合主键(不常用));alter table 表名 add primary key(列名); -- 表创建完成后添加主键索引drop table 表名 drop primary key;
2,唯一索引:加速查找,不能重复,允许最大1个空(多列)联合唯一索引
create table 表名(id int not null auto_increment primary key,name varchar(32) not null,email varchar(64) not null,unique ix_name(name));create table 表名(id int not null auto_increment primary key,name varchar(32) not null,email varchar(64) not null,unique ix_name(name),--唯一索引,每一列的内容不能重复unique ix_emai(email)--多个唯一索引);create table 表名(id int not null auto_increment primary key,name varchar(32) not null,email varchar(64) not null,unique ix_group1(name,email)--多列,联合唯一索引,多列的内容,可以有一部分重复,但不能完全重复);create unique index 索引名 on 表名(列名);drop unique index索引名 on 表名
3,普通索引:加速查找 (多列)联合索引
create table 表名(id int not null auto_increment primary key,name varchar(32) not null,email varchar(64) not null,index ix_name(name));create table 表名(id int not null auto_increment primary key,name varchar(32) not null,email varchar(64) not null,index ix_name(name),--索引index ix_emai(email)--多个索引);create table 表名(id int not null auto_increment primary key,name varchar(32) not null,email varchar(64) not null,index ix_group1 (name,email)--多列,联合索引);create index 索引名 on 表名(列名);drop index索引名 on 表名
7.3索引不命中的情况 1,类型不一致
select * from tb1 where name=123--未命中,效率低,因为表中name为字符串型但主键索引类型不一致时不影响效率
2,使用不等于
select * from tb1 where name!='123'--未命中,效率低,因为使用了不等于但主键索引使用不等于时不影响效率
3,or,当or条件中与未建立索引的列
select * from tb1 where name!='123' or password="xsd"--如果password未建立索引,则效率低
4,排序,根据索引排序时,选择的映射如果不是索引,则不走索引
select * from tb1 order by name --即使name建立了索引,也无法命中,因为选择的是*但使用主键order by时不受影响
5,like,模糊匹配时通配符在前面或中间
select * from tb1 where name like '%uuu' --未命中select * from tb1 where name like '__uuu' --未命中select * from tb1 where name like 'u%-_uu' --未命中select * from tb1 where name like 'uuu%' --命中select * from tb1 where name like 'uuu_' --命中
6,使用mysql内置函数时
select * from tb1 where reverse(name)='asdlf' --未命中但对条件使用内置函数时命中select * from tb1 where name=reverse('asdfj') --命中