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更高效。