mysql 子查詢 EXISTS


子查詢又叫嵌套查詢

子查詢的select 語句不能使用order by子句,order by不要只能對最終查詢結果排序。

1.帶IN的子查詢

select * from emp where dep_id in (select id from dept id); 在子查詢中的order by id排序 對最后結果無影響。

2.帶ANY或ALL的子查詢2

select salary from emp where id in(2,5);

select * from emp where salary <ANY (select salary from emp where id in(2,5));

<ANY 子查詢(匹配任一返回真) :表示條件滿足 小於 子查詢中任何一個值 就會返回emp的一條記錄,相當於篩選出小於子查詢最大值的記錄。

select * from emp where salary <ALL (select salary from emp where id in(2,5));

<ALL 子查詢(匹配所有返回真) :表示條件滿足 小於 子查詢中所有的值 才會返回emp的一條記錄,相當於篩選出子查詢最小值的記錄。

其他操作符功能類似(=,<>,<,>,<=,>=)。

以上用於對子查詢出的集合值不明確,且子查詢的值不多的情況下,不用直接獲取最值而交給數據庫匹配的方法。

3.EXISTS

select * from emp where EXISTS (select id from dept where dept.id=emp.dep_id);

用法: exists后面一定是子查詢語句,不能用(值1,值2)代替;where exists (查詢),結構中沒有列;exists后面的子查詢不返回任何實際數據,只返回真或假,當返回真時 where條件成立,該條記錄保留。

exists (查詢),只要子查詢不會空  則where條件就返回真。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM