简体   繁体   English

性能比较:使用in和like的SQL查询

[英]Performance comparison: SQL query using in and like

Which query runs faster? 哪个查询运行速度更快?

Considering it returns 200 records and authorname is atleast 20 chars long and authorname is fulltext indexed 考虑到它返回200条记录, authorname至少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)

It's not a question of "faster". 这不是“更快”的问题。 They have different meanings. 它们具有不同的含义。

The first query can only run if the subquery returns 0 or 1 records (and should normally use TOP 1 to guarantee this). 仅当子查询返回0或1条记录时才可以运行第一个查询(通常应使用TOP 1来保证这一点)。 However, it can do wildcard matching on the results. 但是,它可以对结果进行通配符匹配。 The second query can run if the subquery returns any number of records, but will not do wildcard matching. 如果子查询返回任意数量的记录,则第二个查询可以运行,但不会进行通配符匹配。

It sounds like what you should really have here is a JOIN: 听起来您这里应该真正拥有的是JOIN:

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

... assuming of course that AuthorID or AuthorName is unique in AuthorTable . ...当然,假设AuthorIDAuthorNameAuthorTable是唯一的。 This will also allow to use LIKE with wildcards for the matching condition, in the case where the quotesauthor field might not always be a direct match with AuthorTable.AuthorName . 在quotesauthor字段可能并不总是与AuthorTable.AuthorName直接匹配的情况下,这还将允许对通配符使用LIKE作为匹配条件。

While I'm here, it's also strange to me that AuthorName would be full-text indexed. 当我在这里时,对AuthorName进行全文索引对我来说也很奇怪。 A traditional index, rather than fulltext, would be more helpful for this query. 对于此查询,传统索引而非全文索引会更有用。 The only reason to use fulltext here is if you have full names like 'John Milton' in that field, and want to be able to do things like search on last name only or first name only. 在此使用全文的唯一原因是,如果您在该字段中拥有全名,例如“ John Milton”,并且希望能够执行诸如仅搜索姓氏或仅名字的操作。 But even in that case, it seems like you'd be much better served by storing those as their own fields and removing the fulltext index. 但是即使在这种情况下,通过将它们存储为它们自己的字段并删除全文索引,似乎也可以为您提供更好的服务。 Fulltext indexes work best on longer fields, like descriptions or articles/posts. 全文索引在较长的字段(例如描述或文章/帖子)上效果最佳。

Not the same. 不一样。 One test equality, other test like expression... 一个测试相等,另一个测试如表达式...

try this for equality 尝试平等

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

try this for like 试试这个喜欢

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

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

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