title: ‘SQL中NOT EXISTS…[EXCEPT]的妙用’
date: 2018-11-13 16:15:30
tags: SQL
categories: 数据库、SQL
toc: true
这是基于github的我的博客:Josonlee’s Bloghtml
EXISTS子查询能够理解为存在,但也不能死扣字眼,多用在where子句中用来删选知足条件的记录,只要子查询能找到就是True,EXISTS条件就成立,反之不成立;NOT EXISTS与之相反git
有如下四张表:github
Product (pID, name, category, UnitType, sID, price ) Order (oID, year, month, day, type, cID, shipType, status) OrderDetail (oID, oDetailNum, pID, unitPrice, quantity) Customer (cID, name, address, phone, creditLimit)
not exists就是【没有、从未】,其后跟随的子查询就是要解决的后半段问题【确定部分】sql
Select pID, name From product Where not exists (select * From order join orderDetail on order.oID = orderDetail.oID Where year=2012 and month=10 and product.pID = orderDetail.pID)
有上面代码能够看出not exists只是解释了需求中的【从未】,而子查询负责【在2012年10月卖出去的产品信息】数据库
若是子查询结果集为空,就是没有售卖的信息,not exists【没有、不存在】知足,条件成立spa
select name, dept_name from student where not exists ( select course_id from course where student.dept_name=course.dept_name except select course_id from takes where student.ID = takes.ID and grade != 'F' )
咱们知道except是求差集,因此能够有以下解释code
where not exists ( 该学生所属的系开设的全部课程C1 except 学生全部及格的课程C2 )
C1-C2为空,就是C1是C2的子集,not exists成立,知足条件htm
好比说公司中若干部门,若干等级的职位blog
{部门全部职位} except {全部B等级的职位}
{全部B等级的职位} except {部门全部职位}
其实很简单,判断时画个图,就知道谁该包含谁了ip
若是还想不通,能够参考这篇分析更细致的文章:查询选修了所有课程的学生姓名
这是基于github的我的博客:Josonlee’s Blog 欢迎前来搭讪