SQL(基于MySQL)—— IN,NOT IN,EXISTS,NOT EXISTS的用法和差别

IN:确定给定的值是否与子查询或列表中的值相匹配,该关键字可以选择与列表中的任意一个值匹配的行;而NOT IN即表示“不在”。

  SELECT ProductID, ProductName FROM Products WHERE CID IN (1, 4, 5);

  SELECT ProductID, ProductName FROM Products WHERE CID IN (SELECT CID FROM Products where Price>100);

  IN (NOT IN) 关键字之后的项目必须用逗号隔开,并且括在括号中。   

  以下查询查找没有出版过商业书籍的出版商的名称:

  SELECT pub_name FROM publishers WHERE pub_id NOT IN (SELECT pub_id FROM titles WHEREtype = 'business')   

 

EXISTS和 NOT EXISTS引入的子查询可用于两种集合原理的操作:交集与差集。两个集合的交集包含同时属于两个原集合的所有元素。   

差集包含只属于两个集合中的第一个集合的元素。 EXISTS:指定一个子查询,检测行的存在。

  SELECT DISTINCT pub_name FROM publishers WHERE EXISTS (SELECT *FROM titles WHERE pub_id = publishers.pub_id AND type = 'business')

  SELECTdistinct pub_name FROM publishers WHERE pub_id IN (SELECT pub_id FROM titles WHERE type = 'business')

  两者的区别:

   EXISTS:后面可以是整句的查询语句如:SELECT *FROM titles

   IN:后面只能是对单列:SELECT pub_id FROM titles

 

NOT EXISTS:例如,要查找不出版商业书籍的出版商的名称

  SELECT pub_name FROM publishers WHERE NOT EXISTS (SELECT * FROM titles WHERE pub_id =publishers.pub_id AND type = 'business')   

  下面的查询查找已经不销售的书的名称:

  SELECT title FROM titles WHERE NOT EXISTS (SELECT title_id FROM sales WHERE title_id =titles.title_id)

 

例子:

//验证有发布产品的公司个数

select id,name from company where exists (select * from product where comid=company.id)

select id,name from company where id in(select comid from product)
//验证没有发布产品的公司个数

select id,name from company where not exists (select * from product where comid=company.id)

select id,name from company where id not in(select comid from product)

 

posted @ 2015-05-09 17:04  RexWei  阅读(242)  评论(0编辑  收藏  举报