【发布时间】:2017-04-20 03:09:22
【问题描述】:
我想用一个视图表来简化我的数据,MainView,但我很难弄清楚。
我有一个特定于客户、语言和状态的Fact 表。 Fact 表中的 ID 来自一个只有 FactLinkID 列的 FactLink 表。 Status 表有一个Order 列,需要在聚合视图中而不是StatusID 中显示。我的Main 表在多个列中引用了Fact 表。
最终目标是能够比以前更简单地通过LanguageID、StatusOrder、ClientID的复合索引查询视图表,获取最大的指定StatusOrder和指定的@ 987654335@ 或 ClientID 1. 所以,这就是我希望通过视图表简化的内容。
所以,
主要
ID | DescriptionID | DisclaimerID | Other
----+---------------+--------------+-------------
50 | 1 | 2 | Blah
55 | 4 | 3 | Blah Blah
事实
FactID | LanguageID | StatusID | ClientID | Description
-------+------------+----------+----------+------------
1 | 1 | 1 | 1 | Some text
1 | 2 | 1 | 1 | Otro texto
1 | 1 | 3 | 2 | Modified text
2 | 1 | 1 | 1 | Disclaimer1
3 | 1 | 1 | 1 | Disclaimer2
4 | 1 | 1 | 1 | Some text 2
事实链接
ID
--
1
2
3
4
状态
ID | Order
---+------
1 | 10
2 | 100
3 | 20
主视图
MainID | StatusOrder | LanguageID | ClientID | Description | Disclaimer | Other
-------+-------------+------------+----------+---------------+-------------+------
50 | 10 | 1 | 1 | Some text | Disclaimer1 | Blah
50 | 10 | 2 | 1 | Otro texto | NULL | Blah
50 | 20 | 1 | 2 | Modified text | NULL | Blah
55 | 10 | 1 | 1 | Some text 2 | Disclaimer2 | Blah Blah
以下是我仅使用一个引用 Fact 表的列来实现它的方法:
DROP VIEW IF EXISTS dbo.KeywordView
GO
CREATE VIEW dbo.KeywordView
WITH SCHEMABINDING
AS
SELECT t.KeywordID, f.ClientID, f.Description Keyword, f.LanguageID, s.[Order] StatusOrder
FROM dbo.Keyword t
JOIN dbo.Fact f
ON f.FactLinkID = t.KeywordID
JOIN dbo.Status s
ON f.StatusID = s.StatusID
GO
CREATE UNIQUE CLUSTERED INDEX KeywordIndex
ON dbo.KeywordView (KeywordID, ClientID, LanguageID, StatusOrder)
我之前的查询查询了除 StatusOrder 之外的所有内容。但是添加StatusOrder 似乎会使事情复杂化。这是我之前没有StatusOrder 的查询。当我在只有一个 Fact 链接列的表上创建视图时,它大大简化了事情,但将其扩展到两列或更多列已被证明是困难的!
SELECT
Main.ID,
COALESCE(fDescription.Description, dfDescription.Description) Description,
COALESCE(fDisclaimer.Description, dfDisclaimer.Description) Disclaimer,
Main.Other
FROM Main
LEFT OUTER JOIN Fact fDescription
ON fDescription.FactLinkID = Main.DescriptionID
AND fDescription.ClientID = @clientID
AND fDescription.LanguageID = @langID
AND fDescription.StatusID = @statusID -- This actually needs to get the largest `StatusOrder`, not the `StatusID`.
LEFT OUTER JOIN Fact dfDescription
ON dfDescription.FactLinkID = Main.DescriptionID
AND dfDescription.ClientID = 1
AND dfDescription.LanguageID = @langID
AND dfDescription.StatusID = @statusID
... -- Same for Disclaimer
WHERE Main.ID = 50
【问题讨论】:
标签: sql sql-server sql-view