在 SQL 语句中使用带有子查询的“IN" [英] Using 'IN' with a sub-query in SQL Statements

查看:50
本文介绍了在 SQL 语句中使用带有子查询的“IN"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在可以使用 JOIN 的地方在 SQL 语句中使用IN"关键字是否有任何性能问题?

Are there any performance issues of using "IN" keyword in SQL statements in places where we can use JOIN?

SELECT xxx
FROM xxx
WHERE ID IN (SELECT Id FROM xxx)

推荐答案

不用,可以使用.

您可以在所有 RDBMS 中使用 IN、EXISTS 编写上述查询,有些还支持 INTERSECT.

You can write the query above using IN, EXISTS in all RDBMS, some also support INTERSECT.

从语义上讲,这是一个半连接,它从表 A 中给我行,我在表 B 中至少有一个匹配项".INNER JOIN 是给我所有匹配的行"

Semantically this is a semi-join which "give me rows from table A where I have a at least one match in tableB". An INNER JOIN is "give me all matching rows"

所以如果 TableA 有 3 行而 TableB 有 5 行匹配:

So if TableA has 3 rows and TableB has 5 rows that match:

  • 一个 INNER JOIN 是 15 行
  • 半连接是 3 行

这就是我和其他 SQL 类型在这里推送 IN 和 EXISTS 的原因:JOIN 是错误的,需要 DISTINCT 并且会更慢.

This is why IN and EXISTS are pushed by me and the other SQL types here: a JOIN is wrong, requires DISTINCT and will be slower.

EXISTS 支持多列 JOIN,IN 在 SQL Server 中不支持(在其他中支持).

EXISTS support multiple column JOINs, IN doesn't in SQL Server (it does in others).

这篇关于在 SQL 语句中使用带有子查询的“IN"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆