使用“IN”在 SQL 语句中使用子查询
在可以使用 JOIN 的 SQL 语句中使用“IN”关键字是否会带来性能问题?
SELECT xxx
FROM xxx
WHERE ID IN (SELECT Id FROM xxx)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不用,用起来就OK了。
您可以在所有 RDBMS 中使用 IN、EXISTS 编写上面的查询,有些还支持 INTERSECT。
从语义上讲,这是一个半连接,“给我表 A 中的行,其中我在表 B 中至少有一个匹配项”。 INNER JOIN 是“给我所有匹配的行”
因此,如果 TableA 有 3 行,TableB 有 5 行匹配:
这就是为什么 IN 和 EXISTS 被我推送的原因,这里的其他 SQL 类型: JOIN 是错误的,需要 DISTINCT 并且会更慢。
EXISTS 支持多列 JOIN,IN 在 SQL Server 中不支持(在其他 SQL Server 中支持)。
No, it's OK to use.
You can write the query above using IN, EXISTS in all RDBMS, some also support INTERSECT.
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"
So if TableA has 3 rows and TableB has 5 rows that match:
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 support multiple column JOINs, IN doesn't in SQL Server (it does in others).
您可以使用 group by 而不是不同的。我曾经遇到过使用 join 获得更好响应时间的情况。通常,当我通过主键/外键关系连接所有行时,where 正在查看非键列。特别是在多个连接的情况下。 IN 有时会强制进行索引扫描,并且如果要进行 PK,连接通常会使用查找。当您设计表时,会将主键排列起来,使它们具有相同的顺序并显式声明 PK / FK 关系。加入不限于PK/FK。但联接的常见用途是遍历 PK/FK 关系,在这种情况下,我的经验是使用键对齐的联接来获得最佳性能。
Rather than a distinct you could use group by. I have had cases where I got better response time using join. Typically when I am joining all the rows via a primary key / foreign key relationship and the where is looking at a non key column. Especially if multiple joins. The IN can SOMETIMES force an index scan and the join will TYPICALLY use a seek if it is going to the PK. When you design you tables line up the primary keys so they are in the same order and explicitly declare the PK / FK relationships. Join are NOT limited to PK / FK. But a common use of a join is to walk the PK / FK relationship and in that case my experience using a join with the keys aligned is the best performance.
正如您可以在此处阅读的那样,JOINS 比子连接更快选择。
As you can read here, JOINS are faster than sub-selects.