SQL Server索引 - 想法?

时间:2017-07-30 07:54:03

标签: sql-server database tsql indexing

我有这个问题:

SELECT 
    c.violatorname
FROM 
    dbo.crimecases AS c,
    dbo.people AS p
WHERE 
    REPLACE(c.violatorname, ' ', '') = CONCAT(CONCAT(CONCAT(p.firstname, p.secondname), p.thirdname), p.lastname);

查询非常慢,我需要使用replace函数在violatorname列上创建索引。有任何想法吗?

1 个答案:

答案 0 :(得分:1)

我建议您添加computed columns并在其上创建index

ALTER TABLE crimecases
  ADD violatornameProcessed AS Replace(violatorname, ' ', '') PERSISTED 

ALTER TABLE people
  ADD fullName AS Concat(firstname, secondname, thirdname, lastname) PERSISTED 

Persisted会将计算出的数据存储在磁盘上,而不是每次都计算。现在在其上创建索引。

CREATE INDEX Nix_crimecases_violatornameProcessed
  ON crimecases (violatornameProcessed)
  include (violatorname)

CREATE INDEX Nix_people_fullName
  ON people (fullName) 

查询可以写成

SELECT c.violatorname
FROM   dbo.crimecases AS c
       INNER JOIN dbo.people AS p
               ON c.violatornameProcessed = p.fullName