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 歡迎前來搭訕