目录
一、MySQL函数:
二、.表连接
前提:有时候我们所需要的数据不止在一张表中,需要多个表做结合的查询,就可以用表连接实现。
表与表之间建立起关联的列,要求列名可以不一样,但是这两个列的数据类型和内容得保持一致
内连接查询:只关联表与表中能够匹配到的数据信息,才能有对应的查询结果
select 表名1.列名1,表名1.列名2,表名2.列名1,表名2.列名2...
select 表名1.列名1,表名1.列名2,表名2.列名1,表名2.列名2...
1.等值连接 指的是条件中只包含等号"=",没有其它符号在里面
2.非等值连接 指的是条件中,除了等号之前,还有其他的符号 > < >=
select 表名1.列名1,表名1.列名2,表名2.列名1,表名2.列名2,表名3.列名1,表名4.列名1...
where 表名1.列名1=表名2.列名1 and 表名2.列名1=表名3.列名1 and 表名3.列名1=表名4.列名1....
三、内连接:
只会显示两个表中匹配到的数值信息
where 表名1.列=表名2.列 and 表名2.列=表名3.列;
四、外部连接:
会返回左表的所有内容,如果在右表中没有匹配到,在对应位置上就显示为null
会返回右表的所有内容,如果在左表中没有匹配到,在对应位置上就显示为null
五、子查询:
select 列名 from 表名 where 列名 in(select查询语句);
例. 查询计算机系学生选修了哪些课程?问:计算机系学生有哪些?
聚合函数不能直接写,就可以借助查询语句把聚合函数的结果给查出来就OK
where grade>(select avg(grade) from sc)
1.select 列名 from 表名 where 列名 in(select 列名 from 表名 where 列名 in(select 列名 from 表名 where 条件));
2.select 列名 from 表名 where 列名 in(select 列名 from 表名 where 条件);
例:select student.sno,sname,grade (把所有要查询的全部写到select后
from sc,student 然后 where后面关联 然后看题中条件where sc.sno=student.sno and sc.grade in 写 到括号里面)and in 连接
(select grade from sc where grade>90);
子查询:指的是子查询中还包含其他的子查询
select(select(select(select)))
当insert语句和select语句做结合,就是把查询的结果插入到某一张表中。
delete from 表名 where 列名 in(select查询语句)
delete from sc where sno in(select sno from student where sdept='计算机系');
六、视图:
指的是根据某个实际的表(实表)查询出来,生成的一个虚表。
create view 视图的名字 as select语句;
1.视图既然作为一张虚表存在,那么对实表的增删改查操作,视图同样成立
2.视图既然是根据实表得到的,那么对视图的增删改操作,也会影响实表。
alter view 视图名字 as select 查询语句;
insert into 视图的名字 values(值1,值2....);
七、索引:
类似于书本中的目录
指的是在数据库表中的一个列或多个列的设置,帮助快速的定位所查询的数据。
4.可以减少group by,order by,分组和排序的时间 (根据某个列来进行分作或者排序)
2.虽然查询的速度加快了,但是减慢了增删改的速度 (书本中插入内容)
create unique index 索引的名字 on 表名(列名);
1.一个表中如果有大量的索引,会影响insert,update,delete语句的性能。
练习题:
all 所有,代表的是把所有的条件匹配成功的情况下,才会有查询结果
select sname from s where s# in(select s# from sc where c#=all(select c# from c));
having count(sc.c#)=(select count(*) from c);
1.先查询出刘老师所较课程的课程号,根据课程号找出对应的选课学生学号,-->姓名
select sname from s where s# in(
select s# from sc where c# in(
select c# from c where tname like '刘%'));
2.先分别查看C2和C4修课的学生有哪些? 我只要既选修了C2,又选修了C4
select sname from s where s# in(select s# from sc where c#='c2') and s# in(select s# from sc where c#='c4');
all 所有,代表的是把所有的条件匹配成功的情况下,才会有查询结果
select sname from s where s# in(select s# from sc where c#=all(select c# from c));