我们正在尝试构建一个以支持简单搜索的扁平化方式提供数据的视图。
挑战在于,当我们显示名称等字段时,我们需要搜索地址等我们没有显示但仍然可以返回的字段。地址存储在地址表中,每个客户记录可以有多个地址。
所以我最初想做一个视图,将主要客户记录与各种地址放在一起。由于连接,这导致了重复的行。
接下来,我编写了一个查询来汇总这些子表并将它们连接在一起。这使得搜索变得容易,并且不会出现任何重复。我把它放到一个视图中,但它很慢。由于访问数据的组件的性质,我更喜欢保留它,但是,我并不完全反对它。
这可以加快速度还是我走错了路?
这是 SQL(实际上是 T-SQL):
WITH ClientBase
AS
(
SELECT DISTINCT Client.ClientID, ClientNames.FirstName, ClientNames.LastName, ClientNames.MiddleName,
AddressHistory.Address1 + ' ' + AddressHistory.Address2 AS StreetAddress,
AddressHistory.City, ContactInfo.Contact AS Phone
FROM Client
INNER JOIN ClientNames ON ClientNames.ClientID = Client.ClientID
INNER JOIN AddressHistory ON AddressHistory.ClientID = Client.ClientID
INNER JOIN ContactInfo ON ContactInfo.ClientID = Client.ClientID
)
SELECT DISTINCT vcs.ClientID, vcs.FirstName, vcs.LastName, vcs.MiddleName,
(SELECT STUFF ((SELECT DISTINCT TOP (100) PERCENT ';' + ClientBase.StreetAddress AS [text()]
FROM ClientBase
WHERE ClientBase.ClientID = vcs.ClientID
FOR XML PATH('')), 1, 1, '') AS StreetAddress) AS StreetAddress,
(SELECT STUFF ((SELECT DISTINCT TOP (100) PERCENT ';' + ClientBase.City AS [text()]
FROM ClientBase
WHERE ClientBase.ClientID = vcs.ClientID
FOR XML PATH('')), 1, 1, '') AS City) AS City,
(SELECT STUFF ((SELECT DISTINCT TOP (100) PERCENT ';' + ClientBase.Phone AS [text()]
FROM ClientBase
WHERE ClientBase.ClientID = vcs.ClientID
FOR XML PATH('')), 1, 1, '') AS Phone) AS Phone
FROM ClientBase AS vcs