我们正在尝试构建一个以扁平化方式提供数据的视图,以支持简单搜索。
我们面临的挑战是,当我们显示名称等字段时,我们需要搜索我们尚未显示的地址等字段,但仍可以返回。地址存储在地址表中,每个客户记录可以有多个地址。
所以我最初想过做一个将主客户端记录与各种地址放在一起的视图。由于连接,这导致重复的行。
接下来,我编写了一个查询,汇总这些子表并将它们连接在一起。这样可以轻松搜索并且不会产生任何重复。我把它放在一个视图中,但它很慢。由于访问数据的组件的性质,我更喜欢保持视图,但是,我并不完全反对它。
这可以加快速度,还是以错误的方式解决这个问题?
这是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