决定稍系统学习下数据库查询知识;
关系数据库系统支持三种模式结构:外模式(试图),内模式(存储文件-索引),模式(基本表)
一 数据定义
1.基本表(定义、删除、修改)
CREAT TABLE student(Sno char(5) NOT UNIQUE,Sname char(20) UNIQUE,Ssex char(1));
ALTER TABLE student ADD Sage char (2);ALTER TABLE student MODIFY Sname SMALLINT;ALTER TABLE student DROP Ssex;
DROP TABLE student;
2.索引(定义、删除)
3.试图-虚表(定义、删除)
二 基本表数据查询
1.单表查询
(1) 选择若干列所有(常量、表达式、函数)
select Sname,ISLOWER(Sdept) from student;
(2) 选择表中的若干元组(一个元组即一行)
可以是元组中所有属性,也可若干属性
i.消除若干重复行select DISTINCT Sname from student where ...
ii.查询满足条件的元组
集合查询中的IN 其实是多个or连接
LIKE=‘全字符’,不含通配符 ; NOT LIKE A 等同于( !=a 或<>a)
is Null 不能写成 = null
当字符匹配中本来就含有%或_的字符,可以用ESCAPE'/'进行转义。/后面的字符则为原字符
iii.对查询结果进行排序
...where b='1' ORDER BY SCORE DESC;(或ASC)
iV.使用集函数(COUNT,SUM,AVG,MAX,MIN)
除了count()可以对全部列进行统计,其他都只能对某列进行
count()注意去重
V.分组 GROUP BY
select Sno,count(Cno) from sc GROUP BY Sno HIVING COUNT(Cno)>3;(不正确,HIVING作用于组,不是表)
select Sno from sc GROUP BY Sno HIVING COUNT(*)>3;
2.多表连接查询
多表查询的条件称为连接谓词,列名称为连接字段
(1)等值连接
select student.*,SC.* from student,SC where student.Sno=SC.Sno;
(2)自然连接(等值连接中去掉重复的列)
select student.Sno,SC.CNO 。。。from student,SC where student.Sno=SC.Sno;
(3)外连接(左,右)
select student.Sno,SC.CNO from student,SC where student.Sno=SC.Sno(*);
(4)自身连接 (间接先修课)
不能通过直接查询,可以将一个表两个别名查询
select S1.Cno,S2.Credit from course S1, course S2where S1.Credit =S2.Cno;
(5)复合条件连接
与上面四个不同的是,以上只有一个连接条件,即一个谓词,而复合条件则称复合条件连接
3.嵌套查询(单表或多表)
(1)IN谓词
select sno from student where sdept in (select sdept from student where name="**");
(2)带有比较运算符的子查询
select sno from student where sdept = (select sdept from student where name="**");
(3)ANY,ALL的子查询
select sname,sage from student where sage<ANY(select sage frome student where sdept="x")
4.集合查询
三 基本表数据更新,包括(插入、修改、删除)
1.插入
单条插入: Insert into student values('','');
子查询插入:Insert into Deptage(sdept,Average) select sdept,avg(age) from student GROUP BY Sdept;
2.修改
update table set age=18 where name="";
update table set age=18;
3.删除
delete from sc where ***;
关系数据库SQL学习
猜你喜欢
转载自wonderfei.iteye.com/blog/1530006
今日推荐
周排行