sql where实现除法的语句执行过程

sql where实现除法的语句执行过程

  • 环境:mysql 5.7

数据库中没有提供全称量词的操作,需要使用否定存在量词实现全称量词的效果以实现数据库除法操作。

否定存在量词sq:lwhere not exists

Schema (MySQL v5.7)

create table student(
  sno int,
  sname varchar(20),
  primary key(sno)
  );
  
 create table course(
   cno int,
   cname varchar(20),
   primary key(cno)
   );
   
 create table sc(
   sno int,
   cno int,
   grade int
  );
  
alter table sc
add primary key(sno,cno);

Query #1

insert into student values
(121,'leo'),
(122,'jack'),
(123,'alice'),
(124,'bob');

There are no results to be displayed.


Query #2

insert into course values
(1,'database'),
(2,'math'),
(3,'it'),
(4,'c');

There are no results to be displayed.


Query #3

insert into sc values
(121,1,99),
(121,2,90),
(121,3,88),
(121,4,87),
(122,2,90),
(122,3,98);

There are no results to be displayed.


Query #4

select * from student;
snosname
121leo
122jack
123alice
124bob

Query #5

select * from course;
cnocname
1database
2math
3it
4c

Query #6

select * from sc;
snocnograde
121199
121290
121388
121487
122290
122398

  • 查询选修了所有课程的学生姓名

Query #7

select sname
from student
where not exists
	( select * 
     from course
     where not exists
     	( select *
         from sc
         where sno=student.sno
         and cno=course.cno));
sname
leo

  • 查询选修了所有课程的学生学号

Query #8

select sno
from sc sc1
where not exists
	( select * 
     from course
     where not exists
     	( select *
         from sc
         where sno=sc1.sno
         and cno=course.cno));
sno
121
121
121
121

View on DB Fiddle


运行流程分析:

运行流程可以用c语言三层循环实现。
query #7分析:
在这里插入图片描述
设i,j,k三个变量,分别代表三个表,
三层循环嵌套执行,若第三层层循环执行完只要有一个true,则返回第二层false,若第二层全为false,则第一层为true,表示输出此元组,进而一直迭代下去,得到最终结果。

所以 query #8 有四条结果,可以使用distinct去重。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值