Mysql exists 操作符詳解


exist 操作符

http://www.mysqltutorial.org/mysql-exists/

SELECT 
    select_list
FROM
    a_table
WHERE
    [NOT] EXISTS(subquery);

exists操作符是一個布林操作符號。用於測試從subquery中返回的行是否存在。

⚠️subyquey是和a_table建立了主外鍵關聯的表

如果subquery至少返回一條記錄,則exists()返回true. 

一旦找到匹配的一行后,就會終止后續的查詢。

子句的select xxx,的xxx可以是任意的,因為Mysql會忽略子句的xxx。

 

a_talbe的每條記錄,都去判斷subquery中是否有對應的記錄,如果有,extist會返回true。生成的查詢結果中會保留對應的select_list。

 

⚠️除了在查詢中使用exists, 在update, delete都可以使用。

 

exists和in比較

首先上結論,處理大數據exists更高效。

根本原因是exists的運行機制:

The reason is that the EXISTS operator works based on the “at least found” principle. The EXISTS stops scanning the table when a matching row found.

找到一條匹配的行后,就停止后面的查詢。

另一方面:

On the other hands, when the IN operator is combined with a subquery, MySQL must process the subquery first and then uses the result of the subquery to process the whole query.

使用in聯合子查詢,程序首先要處理子查詢,然后使用它的結果來處理整個查詢。

所以,在面對大數據時,使用exists更高效。


免責聲明!

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



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