SQL(一)—— 模糊查询

模糊查询
  1.使用like关键字进行模糊查询,需要通配符配合使用
  通配符:
    "_":表示任意一个字符,除了空字符
    "%":表示任意 一个字符串
    "[]":表示指定范围内的一个字符
    "[^]":表示指定范围外的一个字符
  2.使用in关键字进行模糊查询。in表示指定的数据范围

 

多表查询,重点在连接(inner join,right join,left join,full join)
  内连接(inner join):
    select 表1名.列1,表2名.列1... from 表1 inner join 表2
    on 表1.主键=表2.外键;
  右连接查询(right join):
    select 表1名.列1,表2名.列1... from 表1 right join 表2
    on 表1.主键=表2.外键;
  左连接查询(left join)
    注意:指查询的时候以左表为主,把左表的信息都查询出来,其他没有的数据的使用null表示
    select 表1名.列1,表2名.列1... from 表1 left join 表2
    on 表1.主键=表2.外键;
  完全连接查询(full join)
    select 表1名.列1,表2名.列1... from 表1 full join 表2
    on 表1.主键=表2.外键;

视图

  定义:视图就是一个虚拟的表,视图就是封装了一个查询结果。

    也就是是说视图就是对应一个“结果集“。
  作用:方便查询。
  创建:create view 视图名 as 查询指令(一般是连接指令)
  例:create view myview as select stu.sname,stu.sex,stu.tel,kemu.kname,score.fenshu from stu
   inner join score on stu.sid=score.sid inner join kemu
   on kemu.kid=score.kid;

聚合函数(max(),min(),sum(),avg(),count())
  注意:聚合函数只针对列进行运算
  分组查询(group by ),按照某列分组,分组后再分别查询
  查询每个学生的总分。先按照学生分组,每组分别求和
    select sname,sum(fenshu) from myview group by sname ;
  having子句,表示分组查询后再添加查询条件
  比如,查询总分高于200分的学生
    select sname,sum(fenshu) from myview group by sname
    having sum(fenshu)>200;
例:

查询田某同学的基本信息
select * from studentInfo where sname like '田_';--"_":表示任意字符但是不能为空字符
select * from studentInfo where sname like '田%';--"%":表示任意一个字符串
select * from studentInfo where sname like '[天田填舔][陈晨]';--"[]":表示指定范围内的一个字符
select * from studentInfo where sname like '[天田填舔][^陈晨][罐关贯]';
--"[^]":表示指定范围外的一个字符
update scoreInfo set score=score+3 where score in (93,87,56,32);
--使用in关键字进行模糊查询,in表示指定的数据范围
select * from scoreInfo where score between 60 and 80 ;

--内连接查询:inner join
select studentInfo.sno,studentInfo.sname,studentInfo.sage,studentInfo.gender,studentInfo.department,
courseInfo.cno,courseInfo.cname,
scoreInfo.score
from courseInfo inner join scoreInfo on courseInfo.cno=scoreInfo.cno
inner join studentInfo on studentInfo.sno=scoreInfo.sno
order by scoreInfo.sno asc;
--左连接查询:left join
select studentInfo.sno,studentInfo.sname,scoreInfo.cno,scoreInfo.score
from studentInfo left join scoreInfo on studentInfo.sno=scoreInfo.sno
order by studentInfo.sno asc;
--右连接查询:right join
select studentInfo.sno,studentInfo.sname,scoreInfo.cno,scoreInfo.score
from studentInfo right join scoreInfo on studentInfo.sno=scoreInfo.sno
order by studentInfo.sno asc;
--视图
create view myview as
select studentInfo.sno,studentInfo.sname,studentInfo.sage,studentInfo.gender,studentInfo.department,
courseInfo.cno,courseInfo.cname,
scoreInfo.score
from courseInfo inner join scoreInfo on courseInfo.cno=scoreInfo.cno
inner join studentInfo on studentInfo.sno=scoreInfo.sno ;

select * from myview ;
select * from Allview ;

posted @ 2017-11-04 15:21  北宫乾宇  阅读(1679)  评论(0编辑  收藏  举报