1

enter image description here

I have this table in my database where HusbandPersonId and WifePersonId are foreign keys to another table called Person, and the start/end date refer when the marriage start and when it ends.

And I have this query :

SELECT
   DISTINCT A.WifePersonId
FROM
   Couple A
   INNER JOIN Couple B
      ON A.WifePersonId = B.WifePersonId
      AND A.HusbandPersonId <> B.HusbandPersonId
      AND A.StartDate < B.EndDate
      AND A.EndDate > B.StartDate;

which returns any wife that is married to more than one person at same time.

Now I would like to add an index to improve the speed of search of this query.

Which index would be the best and what is the execution plan of the query before and after the index has been added ?

This is a request in homework and I search too much but I didn't find any helpful topic

Can anyone help on this ?

4

1 回答 1

1

一般索引规则建议在连接条件中包含所有字段。这些字段的顺序可能会产生影响。同样,一般规则建议按照增加基数的顺序对字段进行排序(每个字段的唯一值的数量)。

所以你可以试试:

CREATE INDEX Couple__multi ON Couple(StartDate, EndDate, WifePersonId, HusbandPersonId)

这假设不同的开始/结束日期的数量小于唯一的妻子/丈夫 PersonId 的数量。

这些规则基本上是索引 101 类型的东西。大多数情况下,它们会为您提供可接受的性能水平。如果这足以满足您的目的,这在很大程度上取决于您的数据和应用程序。

就个人而言,我并没有过多考虑 SQL 性能分析器建议的索引,但我上次认真研究它们是在 SQL2005 中。我敢肯定,从那以后已经有了一些改进。

希望这可以帮助。

于 2013-01-03T07:48:29.077 回答