鉴于下表(请参见下文),我需要创建一个视图,以显示表MedDRARelations
中的每个代码(SOC,HLGT,HLT,PT和LLT)及其各自的值(Soc_Value,HLGT_value,HLT_Value,表MedDRANames
中的PT_Value和LLT_Value。
我尝试过多次联接MedDRANames
表并创建一个标量函数,该函数返回给定代码(键)的值。
表定义:
CREATE TABLE dbo.MedDRANames
(
[Key] INT NOT NULL,
[Value] VARCHAR(100) NULL,
CONSTRAINT [PK_MedDRANames] PRIMARY KEY CLUSTERED ([Key])
);
CREATE TABLE dbo.MedDRARelations
(
[SOC] INT NOT NULL,
[HLGT] INT NOT NULL,
[HLT] INT NOT NULL,
[PT] INT NOT NULL,
[LLT] INT NOT NULL,
CONSTRAINT [PK_MedDRARelations]
PRIMARY KEY CLUSTERED ([SOC] ASC, [HLGT] ASC, [HLT] ASC, [PT] ASC, [LLT] ASC),
CONSTRAINT [FK_MedDRANameSOC]
FOREIGN KEY ([SOC]) REFERENCES dbo.MedDRANAmes([Key]),
CONSTRAINT [FK_MedDRANameHLGT]
FOREIGN KEY ([HLGT]) REFERENCES dbo.MedDRANAmes([Key]),
CONSTRAINT [FK_MedDRANameHLT]
FOREIGN KEY ([HLT]) REFERENCES dbo.MedDRANAmes([Key]),
CONSTRAINT [FK_MedDRANamePT]
FOREIGN KEY ([PT]) REFERENCES dbo.MedDRANAmes([Key]),
CONSTRAINT [FK_MedDRANameLLT]
FOREIGN KEY ([LLT]) REFERENCES dbo.MedDRANAmes([Key])
);
观看次数:
此视图在22.1 s(SD 1.25)内执行,影响156867行
SELECT
[X].[SOC] AS [Código SOC],
[SOC].[Value] AS [Término SOC],
[X].[HLGT] AS [Código HLGT],
[HLGT].[Value] AS [Término HLGT],
[X].[HLT] AS [Código HLT],
[HLT].[Value] AS [Término HLT],
[X].[PT] AS [Código PT],
[PT].[Value] AS [Término PT],
[X].[LLT] AS [Código LLT],
[LLT].[Value] AS [Término LLT]
FROM
dbo.MedDRARelations AS [X]
INNER JOIN
dbo.MedDRANames AS [SOC] ON [X].[SOC] = [SOC].[Key]
INNER JOIN
dbo.MedDRANames AS [HLGT] ON [X].[HLGT] = [HLGT].[Key]
INNER JOIN
dbo.MedDRANames AS [HLT] ON [X].[HLT] = [HLT].[Key]
INNER JOIN
dbo.MedDRANames AS [PT] ON [X].[PT] = [PT].[Key]
INNER JOIN
dbo.MedDRANames AS [LLT] ON [X].[LLT] = [LLT].[Key]
此视图在35.3 s(SD 2.1)中执行,影响156867行
SELECT
[X].[SOC] AS [Código SOC],
dbo.FindMedDRA(x.SOC) AS [Término SOC],
[X].[HLGT] AS [Código HLGT],
dbo.FindMedDRA(x.HLGT) AS [Término HLGT],
[X].[HLT] AS [Código HLT],
dbo.FindMedDRA(x.HLT) AS [Término HLT],
[X].[PT] AS [Código PT],
dbo.FindMedDRA(x.PT) AS [Término PT],
[X].[LLT] AS [Código LLT],
dbo.FindMedDRA(x.LLT) AS [Término LLT]
FROM
dbo.MedDRARelations AS [X]
标量函数:
CREATE FUNCTION [dbo].[FindMedDRA]
(@code INT)
RETURNS VARCHAR(100)
AS
BEGIN
DECLARE @returning VARCHAR(100)
SELECT @returning = dbo.MedDRANames.Value
FROM dbo.MedDRANames
WHERE dbo.MedDRANames.[Key] = @code
RETURN @returning
END
我想知道什么是实现此目的的正确方法,因为创建联接表耗时12.2 s(SD 0.1),但成本是原始空间的5倍。
谢谢。
更新:执行计划
答案 0 :(得分:0)
第一种方法是正确的方法。单列整数主键上的INNER JOIN
很快,通常通过MERGE JOIN
运算符执行。结果肯定可以证明,肯定比创建函数要快。
答案 1 :(得分:0)
这里最大的问题是MedRARelations
中的值没有索引。注意:一个常见的误解是创建外键会创建索引。不会。
因此,请尝试运行此命令:
CREATE INDEX Idx_MedDRARelations_SOC ON MedDRARelations (SOC);
CREATE INDEX Idx_MedDRARelations_HGLT ON MedDRARelations (HGLT);
CREATE INDEX Idx_MedDRARelations_HLT ON MedDRARelations (HLT);
CREATE INDEX Idx_MedDRARelations_PT ON MedDRARelations (PT);
CREATE INDEX Idx_MedDRARelations_LLT ON MedDRARelations (LLT);
然后再次尝试您的视图和其他方法。