一、内外连接
1.1内连接
查询结果只显示两个表共同满足连接条件的部分
语法1:
Select * from 表1 inner join 表2 on 表1.字段=表2.字段;
例1:Select * from a inner join b on a.id=b.id;
1.2 隐式内连接
语法2:
Select * from 表,表2 where 表1.字段=表2.字段;
1.3 左外连接:
查询的结果为两个表匹配到的数据加左表特有的数据,对于右表中不存在的数据使用 null 填充。
例1:
Select * from student2 left join scores on student2.studentNo=scores.studentNo;
1.4 右外连接:
查询的结果为两个表匹配到的数据加右表特有的数据,对于左表中不存在的数据使用 nul 填充;
例:
Select * from scores right join courses on scores.courseNO=courses.courseNO;
1.4 全连接:
例:
select a.*, ad.* from test_a as a full join test_a_description as ad on a.id=ad.parent_id;
2 索引
2.1 创建索引
语法:
Create index 索引名称 on 表名(字段名称(长度));
索引和表名、字段都相关;如果指定字段是字符串,需要指定长度,建议长度和定义字段的长度一致(不是字符串,可以不填写)。
例1:为表student2的age、name创建索引,名为age_index、name_index
Create index age_index on student2(age);
Create index name_index on student2(name(10));
2.2 索引的调用
例1:where后面的字段,数据库系统会自动查找是否有索引
——这里会自动调用age_index
Select * from student2 where age=30;
——这里会自动调用name_index
Select * from student2 where name=’红红’;
——不会调用任何索引,因为sex没有建立索引
Select * from student2 where sex=’男’;
2.3 查看索引
对于主键会自动建立一个索引
语法:
Show index from 表名;
例1:Show index from student2;
2.4 删除索引
语法:
Drop index 索引名称 on 表名;
例1:
Drop index age_index on student2;
2.5 索引优缺点
提高select查询的速度
会降低update、delete、insert语句的执行速度
项目中80%以上的select,所以index是必须的
实际工作中如果涉及到大量的数据修改工作,可以在修改之前把索引删除,修改完成后再把索引建立起来。