3
Tables A and B in action.
A [commonfield, otherfields]
B [commonfield]

查询 1

select
        A.otherfields
from
        A,B
where
        A.commonfield = B.commonfield
        and some filters ( A.commonfield )

查询 2

select
        A.otherfields
from
        A
where
        A.commonfield in ( select B.commonfield from B )
        and some filters ( A.commonfield )

查询 1 等同于查询 2。在 (a) 内存使用和 (b) 速度方面哪个更好?

4

4 回答 4

5

最好的和 ANSI 标准的做法是

查询 #3:

select
        A.otherfields
from
        A
inner join
        B ON A.commonfield = B.commonfield
where
        some filters ( A.commonfield )
于 2013-04-24T19:01:40.973 回答
1

另一种可能:

SELECT
        A.otherfields
FROM
        A
WHERE EXISTS (SELECT * FROM B WHERE A.commonfield = B.commonfield)
        AND some filters ( A.commonfield )

Where exists 在 SQL Server 中往往最快,但不是在所有数据库中。

我会测试所有的可能性(除了使用隐式连接的那个,它本身就是一种糟糕的编程技术,除非你有一个不能使用显式连接的旧数据库,否则不应该使用))以确定最佳性能您的特定数据库和设置。

于 2013-04-24T19:10:14.747 回答
0

查询 1等于查询 2!

当 B 中有多个匹配项时,Query1 将返回多行。Query 2 将仅返回 A 中的行,没有重复。

由于这些不返回等效的结果集,我认为比较它们的性能不是一个好主意。

但是,查询 1 可能会执行得更好,因为它没有进行重复消除。另一方面,如果您有适当的索引,那么两者可能相似,或者查询 2 甚至可能更好。

于 2013-04-24T21:43:24.027 回答
0

这两个查询将在执行前编译。

性能将取决于查询编译器的 SQL Server 供应商实现。

一个供应商可以将两者优化为要执行的相同代码。

我正在使用 SQL Server 2000,这两个表达式都产生了具有相同性能的等效代码。

于 2013-04-24T19:13:10.023 回答