简体   繁体   English

使用IN SELECT和INNER JOIN之间的区别

[英]Difference between using IN SELECT and INNER JOIN

I want to know if there is performance difference in using 我想知道使用中是否存在性能差异

SELECT Table1.*
FROM Table1
WHERE Col1 IN (SELECT Col2 FROM Table2)

AND

SELECT Table1.*
FROM Table1 INNER JOIN Table2
ON Table1.Col1 = Table2.Col2

The two do different things. 两者做不同的事情。 The in version will not return duplicates. in版本不会返回重复项。 The inner join does return duplicates. inner join不会返回重复项。

Often, the inner join version has better performance, although that depends on the data and the database. inner join版本通常具有更好的性能,尽管这取决于数据和数据库。

I would generally use exists : 我通常会使用exists

SELECT t1.*
FROM Table1 t1
WHERE EXISTS (SELECT FROM Table2 t2 WHERE t2.Col2 = t1.col1);

This can directly take advantage of an index on table2(col2) . 这可以直接利用table2(col2)上的索引。

Usually joins will work faster than subquery. 通常,联接将比子查询更快地工作。 But sometimes the performance may depend on the data in the tables or other factors. 但是有时性能可能取决于表中的数据或其他因素。

You can write your SQL by JOIN or SUBQUERY, SQL Server will always transform it on an execution plan. 您可以通过JOIN或SUBQUERY编写SQL,SQL Server始终会根据执行计划对其进行转换。

You can see more: https://www.essentialsql.com/what-is-the-difference-between-a-join-and-subquery/ 您可以看到更多信息: https : //www.essentialsql.com/what-is-the-difference-between-a-join-and-subquery/

SELECT Table1.*
FROM Table1
WHERE Col1 IN (SELECT Col2 FROM Table2)

In this query, I cannot use any column of table2 in my result set. 在此查询中,我不能在结果集中使用table2的任何列。

If I need column of both table then I will use INNER JOIN. 如果我需要两个表的列,那么我将使用INNER JOIN。

SELECT Table1.*
FROM Table1 INNER JOIN Table2
ON Table1.Col1 = Table2.Col2

In one to one relationship and as per requirement INNER JOIN will perform better. 在一对一关系中,并根据要求,INNER JOIN将表现更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM