DQL数据库查询语言

来源:互联网 发布:淘宝网小众女鞋店 编辑:程序博客网 时间:2024/06/06 07:12

DQL
1.通过as给列加别名,as不可以省略
2.可以直接在表名后面加别名,as不需要写,访问字段的时候通过别名.字段名的方式
3.通过order by t.age进行排序,默认是升序,如果需要降序排列,那么加上desc关键字

4.子查询
用in
--查询所有班级为一班的所有学生信息(子查询)
select * from t_student where classid in
(select clasid from t_class where clasname='一班' or clasname='二班')
 
5.通过case when实现级别展示
如:
select stuname,
  (case
      when levels=1 then '☆'
      when levels=2 then '☆☆'
      when levels=3 then '☆☆☆'
      when levels=4 then '☆☆☆☆'
      when levels=5 then '☆☆☆☆☆'
      else '没有参加考试'
      end) 星级
from t_student

6 聚合函数
    --count 聚合函数统计数量
--sum   聚合函数求和
--avg   统计平均值


7分组 group by
--统计每个班级的人数 通过分组来实现 group by
select classid ,count(*), avg(age),sum(age) from t_student group by classid
 
8 连接
如:
--内连接简写
--两个表关联的时候必须有关联条件 否则不可以关联,
--如果两个表里的数据对应不起来则不会匹配查询
select t.*,c.clasname from t_student t ,t_class c where t.classid=c.clasid
--左外连接 左边的表为主表,右边的表为从表,主表的数据会全部显示
select t.*,c.clasName from  t_class c left join  t_student t on t.classid=c.clasid
select t.*,c.clasname from t_student t ,t_class c where t.classid=c.clasid(+)
--右外连接 右边边的表为主表,左边的表为从表,主表的数据会全部显示
select t.*,c.clasName from  t_class c right join  t_student t on t.classid=c.clasid
select t.*,c.clasname from t_student t ,t_class c where t.classid(+)=c.clasid
--全连接 两边数据会全部显示
select t.*,c.clasName from  t_class c full join  t_student t on t.classid=c.clasid
 
 ---查询所有参加过活动的人exists  not exists
 select * from t_student t where  exists (
      select 1 from t_active ac where t.stuname= ac.stuname
 )

原创粉丝点击