2017-06-02 38 views
2

哪个查询运行速度更快?性能比较:SQL查询中使用的和如

考虑返回200个记录和authorname是ATLEAST 20个字符长,authorname是全文索引

select * from quotestable 
where quotesauthor like (select Authorname from Authortable where authorid =45) 

select * from quotestable 
where quotesauthor in (select Authorname from Authortable where authorid =45) 
+4

为什么不看看每个执行计划? – flaZer

+0

不是问题的一部分,但它可能会产生不同的结果。 – Durus

回答

8

这不是“更快”的问题。它们有不同的含义。

第一个查询只能在子查询返回0或1条记录时运行(通常应使用TOP 1来保证这一点)。但是,它可以对结果进行通配符匹配。如果子查询返回任意数量的记录,则第二个查询可以运行,但不会执行通配符匹配。

这听起来像你要真有在这里是一个JOIN:

SELECT q.* 
FROM quotestable q 
INNER JOIN AuthorTable a ON q.quotesauthor = a.authorname 
WHERE a.authorid = 45 

...假设当然是AuthorIDAuthorNameAuthorTable独一无二的。如果quotesauthor字段可能不总是与AuthorTable.AuthorName直接匹配,那么这也将允许使用LIKE和匹配条件的通配符。

虽然我在这里,但我也很奇怪AuthorName将被全文索引。传统索引而不是全文索引对此查询更有帮助。在这里使用全文的唯一理由是,如果你在这个领域有全名,比如'约翰米尔顿',并且希望能够完成像姓或名字搜索这样的事情。但即使在这种情况下,通过将这些字段存储为自己的字段并删除全文索引,您似乎也会更好。全文索引在较长的字段上效果最佳,如描述或文章/帖子。

0

不一样。一个测试平等,其他测试一样表现......

尝试一下本作平等

select * from quotestable f1 
where exists 
(
select * from Authortable f2 
where f2.authorid =45 and f1.quotesauthor =f2.Authorname 
) 

试试这个像

select * from quotestable f1 
where exists 
(
select * from Authortable f2 
where f2.authorid =45 and f1.quotesauthor like '%' + f2.Authorname + '%' 
)