mysql之exists子查询和in查询的对比

exists和not exists对应 in 和not in

不同在于,在select 查询中,exists和in的执行顺序不同。

[sql] 
mysql> select * from category;  
+----+---------+  
| id | c_name  |  
+----+---------+  
|  1 | ios     |  
|  2 | android |  
|  3 | sb      |  
+----+---------+  
3 rows in set  
 
商品表: www.2cto.com  
[sql] 
mysql> select * from goods;  
+----+---------+--------+-------+-----+  
| id | name    | cat_id | price | num |  
+----+---------+--------+-------+-----+  
|  1 | 苹果    |      1 |  4999 |   2 |  
|  2 | nexus4  |      2 |  1999 |   3 |  
|  4 | 荣耀2   |      2 |  1888 |   5 |  
|  6 | 三星    |      2 |  3000 |   2 |  
+----+---------+--------+-------+-----+  
6 rows in se  
  www.2cto.com  
要求:只找出分类下有商品的分类
 
[sql] 
mysql> select * from category c where exists (select * from goods where cat_id=c.id);  
+----+---------+  
| id | c_name  |  
+----+---------+  
|  1 | ios     |  
|  2 | android |  
+----+---------+  
2 rows in set 

先执行select查询,结果再和子句中的select结果比较。和in相反。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章