SQL中的EXISTS子句和IN子句有什么区别?

什么时候应该使用EXISTS,什么时候应该使用IN?


当前回答

EXISTS is much faster than IN when the subquery results is very large. IN is faster than EXISTS when the subquery results is very small. CREATE TABLE t1 (id INT, title VARCHAR(20), someIntCol INT) GO CREATE TABLE t2 (id INT, t1Id INT, someData VARCHAR(20)) GO INSERT INTO t1 SELECT 1, 'title 1', 5 UNION ALL SELECT 2, 'title 2', 5 UNION ALL SELECT 3, 'title 3', 5 UNION ALL SELECT 4, 'title 4', 5 UNION ALL SELECT null, 'title 5', 5 UNION ALL SELECT null, 'title 6', 5 INSERT INTO t2 SELECT 1, 1, 'data 1' UNION ALL SELECT 2, 1, 'data 2' UNION ALL SELECT 3, 2, 'data 3' UNION ALL SELECT 4, 3, 'data 4' UNION ALL SELECT 5, 3, 'data 5' UNION ALL SELECT 6, 3, 'data 6' UNION ALL SELECT 7, 4, 'data 7' UNION ALL SELECT 8, null, 'data 8' UNION ALL SELECT 9, 6, 'data 9' UNION ALL SELECT 10, 6, 'data 10' UNION ALL SELECT 11, 8, 'data 11' Query 1 SELECT FROM t1 WHERE not EXISTS (SELECT * FROM t2 WHERE t1.id = t2.t1id) Query 2 SELECT t1.* FROM t1 WHERE t1.id not in (SELECT t2.t1id FROM t2 ) If in t1 your id has null value then Query 1 will find them, but Query 2 cant find null parameters. I mean IN can't compare anything with null, so it has no result for null, but EXISTS can compare everything with null.

其他回答

基于规则优化器:

当子查询结果非常大时,EXISTS比IN快得多。 当子查询结果很小时,IN比EXISTS快。

基于成本优化器:

没有区别。

在某些情况下,使用In比使用EXISTS更好。通常,如果选择谓词在子查询中,则使用In。如果选择谓词在父查询中,则使用EXISTS。

https://docs.oracle.com/cd/B19306_01/server.102/b14211/sql_1016.htm#i28403

如果你可以用where in代替where exists,那么where in可能更快。

使用where in或where exists 将遍历父结果的所有结果。不同之处在于where exists将导致大量依赖子查询。如果你可以防止依赖子查询,那么where in将是更好的选择。

例子

假设我们有10,000家公司,每家公司有10个用户(因此我们的用户表有100,000个条目)。现在假设您希望通过用户名或公司名查找用户。

下面使用were exists查询的执行时间为141ms:

select * from `users` 
where `first_name` ='gates' 
or exists 
(
  select * from `companies` 
  where `users`.`company_id` = `companies`.`id`
  and `name` = 'gates'
)

这是因为对每个用户执行一个依赖子查询:

然而,如果我们避免exists查询并使用:

select * from `users` 
where `first_name` ='gates' 
or users.company_id in  
(
    select id from `companies` 
    where  `name` = 'gates'
)

然后避免依赖子查询,查询将在0,012毫秒内运行

我认为,

EXISTS是当您需要将查询结果与另一个子查询匹配时。 查询#1的结果需要在SubQuery结果匹配的地方检索。有点像Join.. 例如,选择表1中也下过表2订单的客户 IN用于检索特定列的值是否位于列表(1,2,3,4,5)中 例如,选择位于以下邮政编码中的客户,即zip_code值位于(....)列表中。

什么时候使用一种而不是另一种……当你觉得读起来合适的时候(更好地传达意图)。

如果子查询返回多个值,则可能需要执行外层查询—如果条件中指定的列中的值与子查询结果集中的任何值匹配。要执行此任务,需要使用in关键字。

您可以使用子查询来检查一组记录是否存在。为此,您需要使用exists子查询子句。exists关键字总是返回true或false值。