mysql exists與not exists
- 來源:縱橫數(shù)據(jù)
- 作者:中橫科技
- 時間:2018/1/5 9:43:07
- 類別:新聞資訊
mysql exists與not exists
tableA
|column1 | column1 |column3 |
tableb
|column1 | column1 |column3 |
要查詢 tableA 的數(shù)據(jù),條件是是 tableA.column1 不在 tableB 的 tableB.column2 中
也就是要得到類似以下語句的效果(not in 效果不完全等同于 not exists , 如果子查詢中出現(xiàn)空記錄, 則整個查詢語句不會返回數(shù)據(jù))
1 2 3 4 5 6 7 8 | SELECT a.* FROM tableA a WHERE a.column1 not in ( SELECT column2 FROM tableB ) |
可以使用如下語句來實現(xiàn)
1 2 3 4 5 6 7 8 | SELECT a.* FROM tableA a WHERE NOT EXISTS( SELECT b.column2 FROM tableB b WHERE a.colunm1=b.column2 ) |
以上只是兩張表的情況, 其實在多張表的連接查詢中也是比較好用的. 以上寫法同樣適用于exists