mysql之exists子查詢和in查詢的對比

2021-06-16 18:16:37 字數 1202 閱讀 4129

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相反。

子查詢及exists

子查詢分為無關子查詢和相關子查詢 無關子查詢,只查詢一次,與外查詢無關,可作為查詢條件 select from student where sno in select sno from student where class 98789 也可作為乙個虛擬表使用。select from student...

帶有exists謂詞的子查詢 巢狀查詢

exists,not exists 1.含義 帶有exists謂詞的子查詢不返回任何實際資料,它只產生邏輯真值true或邏輯假值false。2.查詢所有選修了c1號課程的學生姓名 select sn from s where exists select from sc where sno s.sno...

MySQL使用exists優化in查詢

mysql 優化時,總是說在某些情況下要用 exists 代替 in,下面我會介紹一下,exists 替換 in 時需要注意的問題。1 建立表結構 使用者資訊表 create table user info id char 36 not null,name varchar 20 not null,a...