关于非规范化。我怎样才能使这个查询更短或更好? (SQL SERVER 2000)[关闭]
Posted
技术标签:
【中文标题】关于非规范化。我怎样才能使这个查询更短或更好? (SQL SERVER 2000)[关闭]【英文标题】:On Denormalization. How can I make this query shorter or better? (SQL SERVER 2000) [closed] 【发布时间】:2011-09-14 09:54:48 【问题描述】:INSERT INTO
denormalizedTable
SELECT
table1.userName,
MAX(CASE WHEN table2.Type = 1 THEN table2.Question END) AS question_1,
MAX(CASE WHEN table2.Type = 1 THEN table2.Answer END) AS answer_1,
MAX(CASE WHEN table2.Type = 2 THEN table2.Question END) AS question_2,
MAX(CASE WHEN table2.Type = 2 THEN table2.Answer END) AS answer_2,
MAX(CASE WHEN table2.Type = 3 THEN table2.Question END) AS question_3,
MAX(CASE WHEN table2.Type = 3 THEN table2.Answer END) AS answer_3,
MAX(CASE WHEN table2.Type = 4 THEN table2.Question END) AS question_4,
MAX(CASE WHEN table2.Type = 4 THEN table2.Answer END) AS answer_4,
MAX(CASE WHEN table2.Type = 5 THEN table2.Question END) AS question_5,
MAX(CASE WHEN table2.Type = 5 THEN table2.Answer END) AS answer_5,
MAX(CASE WHEN table2.Type = 6 THEN table2.Question END) AS question_6,
MAX(CASE WHEN table2.Type = 6 THEN table2.Answer END) AS answer_6,
MAX(CASE WHEN table2.Type = 7 THEN table2.Question END) AS question_7,
MAX(CASE WHEN table2.Type = 7 THEN table2.Answer END) AS answer_7,
MAX(CASE WHEN table2.Type = 8 THEN table2.Question END) AS question_8,
MAX(CASE WHEN table2.Type = 8 THEN table2.Answer END) AS answer_8
FROM
table1
JOIN
table2
ON
table1.userID = table2.userID
GROUP BY table1.userName
【问题讨论】:
您是否考虑过将其作为索引视图来维护,而不是您必须维护的新表? technet.microsoft.com/en-us/library/cc917717.aspx 您认为denormalizedTable
属于哪种范式?
【参考方案1】:
您正在 SQL 中执行“PIVOT”操作。没有真正更好的方法可以做,所以你不能真正让它变得更好。
也许您可以 GROUP BY table1.userID 而不是 userName!
问题是:为什么需要这样的查询?
如果您正在为客户端执行查询以在视图中返回结果,则枢轴操作必须是视图的工作,而不是 DAL。
我们需要更多的上下文来回答你!
【讨论】:
这甚至不是一个答案。为什么投票赞成?谁删除了评论?以上是关于关于非规范化。我怎样才能使这个查询更短或更好? (SQL SERVER 2000)[关闭]的主要内容,如果未能解决你的问题,请参考以下文章