[英]Like Query in SQL taking time
So I've looked around to try to find some posts on this and there are many Like Query 1 and Like Query 2 but none that address my specific question (that I could find). 因此,我环顾四周,尝试查找有关此问题的帖子,并且有很多“ 赞查询1”和“ 赞查询2”,但没有一个解决我的特定问题(可以找到)。
I have two tables in which I have around 5000000+ records and I am returning Search result from these tables as : 我有两个表,其中有大约5000000+条记录,并且我从这些表返回的搜索结果为:
SELECT A.ContactFirstName, A.ContactLastName
FROM Customer.CustomerDetails AS A WITH (nolock)
WHERE (A.ContactFirstName + ' ' + A.ContactLastName LIKE '%' + 'a' + '%')
UNION
SELECT C.ContactFirstName, C.ContactLastName
FROM Customer.Contacts AS C WITH (nolock)
WHERE (C.ContactFirstName + ' ' + C.ContactLastName LIKE '%' + 'a' + '%')
My problem is it is taking around 1 minute to execute. 我的问题是执行大约需要1分钟。
For above query I am expecting result like : 对于上述查询,我期望的结果是:
Please suggest me the best practice to improve performance. 请向我建议提高性能的最佳做法。 Thanks in advance. 提前致谢。
NOTE : No missing Indexes. 注意 :没有丢失的索引。
when you use "LIKE '%xxx%'" index are not used that why your query is slow i think. 当您使用“ LIKE'%xxx%'”索引时,我认为为什么查询缓慢。 When you use "LIKE 'xxx%')" index is used (if an index exist on column of course. >Other proble you do a like on concatenante column, i dont knwo if index is used in this case. And why do a 'xxx' + ' ' + 'yyy' like 'z%', just do 'xxx' like 'z%' its the same. You can try to modify your query like this 当您使用“ LIKE'xxx%')”索引时(如果当然在该列上存在索引。>其他问题,您在concatenante列上执行类似操作,如果在这种情况下使用了索引,我也不知道。为什么'xxx'+''+'yyy'就像'z%',就像做'xxx'就像'z%'一样。您可以尝试像这样修改查询
SELECT A.ContactFirstName, A.ContactLastName
FROM Customer.CustomerDetails AS A WITH (nolock)
WHERE A.ContactFirstName LIKE '%a%' or A.ContactLastName LIKE '%a%'
UNION
SELECT C.ContactFirstName, C.ContactLastName
FROM Customer.Contacts AS C WITH (nolock)
WHERE C.ContactFirstName LIKE 'a%'
Use Charindex which improves performance of the search ,Here it checks the string to match with first charcter of given search charecter and doesn't search for any more matches. 使用Charindex可以提高搜索性能,在此它检查字符串是否与给定搜索字符的第一个字符匹配,并且不再搜索其他匹配项。
DECLARE @Search VARCHAR(10)='a'
SELECT A.ContactFirstName, A.ContactLastName
FROM Customer.CustomerDetails AS A WITH (NOLOCK)
WHERE CHARINDEX(@Search,(A.ContactFirstName + ' ' + A.ContactLastName),0)>1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.