目录

  • ​​单表查询​​
  • ​​一般格式​​
  • ​​选择表中的如干列​​
  • ​​查询指定列​​
  • ​​查询全部列​​
  • ​​查询经过计算的值​​
  • ​​选择表中的若干元组​​
  • ​​消除取值重复的行​​
  • ​​查询满足条件的元组​​
  • ​​常用的查询条件​​
  • ​​比较大小​​
  • ​​确定范围​​
  • ​​确定集合​​
  • ​​字符匹配​​
  • ​​涉及空值查询​​
  • ​​多条件查询​​
  • ​​order by 子句​​
  • ​​聚集函数​​
  • ​​group by 子句​​

单表查询

一般格式

select  all/distinct  目标表达式
from 表名或视图名
where 条件表达式
order by 排序表达式
group by 分组对象 [having<条件表达式>]

第三章 单表查询_元组

第三章 单表查询_表名_02

选择表中的如干列

查询指定列

select 指定列名(逗号分隔)     --如Sname,Sno
from 表名

查询全部列

select*   --*表示所有列,或者写出所有列名
from 表名

查询经过计算的值

select 计算表达式(如2020-sage 表示 出生年份)
from 表名
----------------------------------------
--注:
--重新规定查询显示的列名
select 目标表达式 规定列名
select (目标表达式)as 规定列名
--小写查看
select lower(目标表达式)
--
select '字符串' --显示一列该字符串

选择表中的若干元组

消除取值重复的行

select  all/distinct 目标表达式
all --选择全部 默认
distinct --去掉重复行

查询满足条件的元组

常用的查询条件

第三章 单表查询_表名_03

比较大小
select 目标表达式
from 表名
where 条件表达式
--如
where Sage=20
where Sname='张三'
where Sage<20
确定范围
select 目标表达式
from 表名
where 条件表达式
--如
where Sage between 20 and 30
where Sage not between 20 and 30
确定集合
select 目标表达式
from 表名
where 条件表达式
--如
where Sdept in ('CS','MA','IS')
where Sdept not in ('CS','MA','IS')
字符匹配
--通配符
% --代表任意长度的字符串
_ --代表任意单个字符
select 目标表达式
from 表名
where 条件表达式
--如
where Sname like '欧阳_' --表示姓欧阳 名字为三个字
where Sname like '欧阳%' --表示姓欧阳 不规定字数
where Sname like '_阳%' --表示名字第二个字为阳
--转义字符
select
where Cname like 'DB\_%i__'escape'\' --表示转义字符为\ 将\后第一个字符不作为通配符使用
涉及空值查询
select 目标表达式
from 表名
where 条件表达式
--如
where Grade is null
where Grade is not null
多条件查询
and or        --可用来连接多个查询条件 and优先级高于or
not --取反
--------------
select 目标表达式
from 表名
where 条件表达式
--如
where Sdept='CS' and Sage<20
where Sdept='CS' or Sdept='MA' or Sdept='IS' --等价于where Sdept in ('CS','MA','IS')

order by 子句

用户可以用 order by 子句对查询结果按照一个或者多个属性列的升序(asc)或者降序(desc)排序,默认值为升序

asc   --升序
desc --降序
select 目标表达式
from 表名
where 条件表达式
order by 排序表达式
--如
order by Gread desc --按照分数降序排列
order by Sdep,Sage desc --按所在系的系号升序排列,同一系的学生按年龄降序排序

聚集函数

第三章 单表查询_表名_04

select 目标表达式      --如Sname,Sno
from 表名
--如
select count(*)
from Student --查询学生总人数

select count(distinct Sno)
from SC --查询选修课程的学生人数

select avg(Grade)
from SC
where Con='1' --查询选修一号课程的学生平均分数

select max(Grade)
from SC
where Con='1' --查询选修一号课程的学生最高分数

select sum(Ccredit)
from SC,Course
where Sno='201215012'and SC.Cno=Course.Con --查询学生201015012选修课程的总分数

注:

第三章 单表查询_表名_05

group by 子句

--查找各课程号和相应选课人数
select Cno,Count(Sno)
from sc
group by Con --根据课程号分组
-------------------------------------
--查找选修了三门以上课程的学生号
select Sno
from sc
group by Sno --group by语句进行分组
having count(*)>3 --having语句给出选择组的条件
-------------------------------------
--查询平均成绩大于等于九十分的学生学号和平均成绩
select Sno,avg(Grade)
from Sc
group by Sno
having avg(Grade)>=90

注:

where子句月having短语的区别在于作用对象不同
  where子句作用于基本表或视图,从中选择满足条件的元组
  having 短语作用于组,从中选择满足条件的组