SQL语句例题:
-
同时选修08305001和08305002的课的同学姓名,学号
select X.xh,S.xm from E X,E Y,S where X.xh=Y.xh and X.kh='08305001' and Y.kh='08305002' and S.xh=X.xh;
-
至少使用零件编号P3和P5的工程编号JNO(和上一题同类型)
select distinct X.jno from SPJ X,SPJ Y where X.jno=Y.jno and X.pno='P3' and Y.pno='P5';
-
驾驶了所有汽车的驾驶员姓名和驾驶证号
分为三个步骤:
-
查找驾驶员驾驶汽车的所有记录
select * from BC where dno=D.dno and cno=C.cno;
-
查找驾驶员没驾驶的汽车的记录(在所有汽车里面找没有驾驶记录的车)
select * from C where not exists(select...);
-
查找驾驶了所有汽车的驾驶员
select dname,dno from D where not exists(select * from C where not exists(select * from D,BC where D.dno=BC.dno and ));
-
-
全部驾驶员都驾驶过的汽车的车牌号,车类型
分为三个步骤:
-
查找驾驶员驾驶汽车的记录
select * from BC where dno=D.dno and cno=C.cno;
-
查找没驾驶全部车的驾驶员(如果驾驶了全部车 那应该任何一个not exists都不会满足 所以不会出现在这里)
select * from D where not exists(select...);
-
查找所有驾驶员都驾驶过的汽车
select cname,cno from C where not exists(select * from D where not exists(select * from BC where dno=D.dno and cno=C.cno));
-
-
查询2018年为超过10个部门服务的车牌号,车型,服务的部门数量,按照部门数量降序,如果数量相同按照车牌号升序
select cno,ctype,count(distinct(bno)) as b_number from C,BC where year(rq)='2018' and C.cno=BC.cno group by cno having b_number>10 order by b_number desc,cno asc;
-
更新部门B09订购的’2020-10-6’的车,改为所有车中价格最高的车
update BC set CNO=SOME(select price from C where price=MAX(select price from C)) where rq='2020-10-6' and bno='B09';
-
不使用编号P3零件的工程编号和姓名
select jno,jname from J where not exists(select * from SPJ where SPJ.jno=J.jno and SPJ.pno='P3');
-
至少不使用P3和P5零件的工程编号JNO
select jno from J where jno not in(select jno from spj where pno in('p3','p5'));
-
使用所有零件的工程名称
三步拆解:
-
SPJ中所有供应记录
select * from SPJ where J.jno=SPJ.jno and P.pno=SPJ.pno;
-
没被全部用到的零件的记录集合
select * from P where not exists(select...)
-
使用了全部零件的工程集合
select jname from J where not exists(select * from P where not exists(select * from SPJ where J.jno=SPJ.jno and P.pno=SPJ.pno));
-
-
查询至少使用了一种“东方配件厂“的零件的工程编号
select distinct jno from SPJ where sno=ANY(select sno from S where sname="东方配件厂");
-
WAN同学没有选修的课号
SQL中 否定和没有 先一个EXISTS 里面一个NOT EXISTS
select cno from C where exists( select * from S where exists S.sname='WAN' and not exists( select * from SC where SC.sno=S.sno and C.cno=SC.cno));
-
至少使用了供应商编号为S1所供应的全部零件的工程编号JNO
三步拆解:
-
SPJ中所有的S1使用的零件
select * from SPJ Z where Z.pno=Y.pno;
-
没用到全部的S1零件的记录
select * from SPJ Y where Y.sno='S1' and not exists(select...);
-
用到了全部的零件的记录
select distinct jno from SPJ X where not exists(select * from SPJ Y where Y.sno='S1' and not exists(select * from SPJ Z where Z.jno=X.jno and Z.pno=Y.pno));
-
数据库关系代数
-
所有和包含关系 至少有 全部 所有…(用除法)
-
不 没有… 否定和非的关系 用差(减)
-
同时选两门课 同时有两条记录(用笛卡尔积 根据列序号选择)
数据库SQL语句
-
聚合函数 GROUP BY和HAVING
-
所有xxx NOT EXISTS(NOT EXISTS)
把EXISTS理解为 在自查询中找得到的 NOT EXISTS就是在自查询中找不到的
-
最大最小 MAX MIN ANY ALL
-
修改某个地方的值
-
不 没有… 一个NOT EXISTS
一定要记得 GROUP BY 和 HAVING