码迷,mamicode.com
首页 > 数据库 > 详细

数据库原理-数据单表查询

时间:2016-08-28 19:26:14      阅读:309      评论:0      收藏:0      [点我收藏+]

标签:

格式:select [all|distinct] <目标列表达式>,[目标列]...

from <表名或视图名>[,<表名或视图名>|(seslect 语句)[as]<别名>]

[where <条件名>]

[group by<列名1>[having <条件表达式>]]

[order by<列名1>[asc|desc]]

单表查询

选择表中的若干列

1.查询全部列

select * from student

2.查询经过计算的列

select 2012-age from student  // 2012-age不是列名,而是一个表达式,计算学生的出生年份 

选择表中的若干元组

1.取消取值重复的行

select distinct sno from sc //去掉表中重复的行必须制定短语distinct,如果没有指定,缺省值为all

2.查询满足条件的元组

    • 比较大小
select sname age from student where age<20
    • 确定范围

查找年龄在20-23岁(包括20和23岁)之间的学生的姓名,系别

select sname,sdept  from student where age between 20 and 23

查找年龄不在20-23岁(包括20和23岁)之间的学生的姓名,系别

select sname,sdept  from student where age not between 20 and 23

    • 确定集合

select sname,sex from student where sdept in(‘is‘,‘math‘)//谓词in 用来查找属性值属于指定集

select sname,sex from student where sdept not in(‘is‘,‘math‘)//谓词in 用来查找属性值属于指定集   

    • 字符匹配

格式:like ‘匹配串‘

匹配串既可以是一个完整的字符串,也可以含有通配符%和_

%(百分号)代表任意长度(可以为0)的字符串

_(下横线)代表任意单个字符

查询学号为001的学生的信息

select * from student where sno=‘001‘  //匹配串中不含通配符时,可以用=代替like,用!=或>,<代替not like

查找所有姓刘的学生的信息

select * from student where sname like ‘刘%‘

查询姓张且全名为3个汉字的学生的姓名

select sname from student where sname like ‘张_ _ _ _‘ //一个汉字占两个字符的位置   

    • 空值查询

select sno,cno from sc where grade is null  //注意,这里的is不能用等号=代替

    • 多重条件查询

and 和 or可以连结多个查询条件,and的优先级高于or,用户可以用括号改变优先级

查询计算机系年龄在20岁以下的学生的姓名

select sname from student where sdept=‘cs‘ and age<20        

order by

select sno,grade from sc where cno=‘3‘ order by grade desc

对于空值,升序排列,含空值的元组将最后显示;降序排列,含空值的元组将最先显示

聚集函数

count distinct/all *       计算元组个数
count distinct/all 列名    统计一列中值的个数
sum   distinct/all 列名    计算一列值的总和,此列必须是数值型
avg   distinct/all 列名    计算一列值的平均值,此列必须是数值型
max   distinct/all 列名    计算一列值的最大值
min   distinct/all 列名    计算一列值的最小值
 

如果指定distinct,计算时取消重复值,默认为all,表示不取消重复值

查询学生总人数

select count * from student

查询选修了课程的学生人数

select count(distinct sno) from sc

计算1号课程的学生平均成绩

select avg(grade) from sc where cno=‘1‘

查询选修1号课程的学生最高分数

select max(grade) from sc where cno=‘1‘

group by 字句

求各个课程号及相应的选课人数
select cno,count(sno)from sc group by cno        
 
查询选修了3门以上课程的学生学号
select sno from sc group by sno having count(*)>3   //having短语指定选择组的条件,只有满足条件的组才会被选出来 
 
where子句和having短语的区别在于作用对象的不同。where子句作用于基本表或视图,从中选择满足条件的元组。having短语作用于组,从中选择满足条件的组。

 

 

数据库原理-数据单表查询

标签:

原文地址:http://www.cnblogs.com/x739400043/p/5815638.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!