我想知道是否有更快或更好的方法来处理以下情况:
我目前发现自己正在努力优化冗长的选择查询的执行时间,我需要为每条记录的每个唯一字段进行左连接(基本上是旋转表)。有没有办法通过单个连接/枢轴来最小化这个,以减少检索数据所需的时间?
我需要提供50个自定义字段,这些字段超过30000个奇数记录(这是相关列上的索引)
我将不胜感激任何帮助(包括更正标题,因为我不确定如何另行说明)提前致谢。
下面是设置一个小例子的代码:
Create Table CustomField (
ID int identity (1,1) Not Null,
FieldName varchar(50) Not null,
FieldOrderNumber int Not Null);
ALTER TABLE [dbo].[CustomField] ADD CONSTRAINT [PK_CustomField] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
GO
Create Table FieldValue (
ID int identity (1,1) Not Null,
CustomFieldID int Not Null,
PersonID int Not Null,
FieldValue varchar(50));
ALTER TABLE [dbo].[FieldValue ] ADD CONSTRAINT [PK_FieldValue] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
GO
Create Table Person (
ID int identity (1,1) Not Null,
PersonName varchar (50) Not Null);
ALTER TABLE [dbo].[Person] ADD CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
GO
Insert into Person (PersonName)
Values ('Marc');
Insert into Person (PersonName)
Values ('John');
Insert into CustomField (FieldName, FieldOrderNumber)
Values ('BloodType',1);
Insert into CustomField (FieldName, FieldOrderNumber)
Values ('EyeColour',2);
Insert into FieldValue (CustomFieldID , PersonID, FieldValue)
Values (1,1, 'A+');
Insert into FieldValue (CustomFieldID , PersonID, FieldValue)
Values (1,2, 'O-');
Insert into FieldValue (CustomFieldID , PersonID, FieldValue)
Values (2,1, 'Blue');
Insert into FieldValue (CustomFieldID , PersonID, FieldValue)
Values (2,2, 'Hazel');
WITH ListFieldValues (FieldOrderNumber, FieldName, PersonID, FieldValue)
AS
(
SELECT cf.FieldOrderNumber, cf.FieldName, fv.PersonID, fv.FieldValue
FROM CustomField cf LEFT JOIN FieldValue fv ON cf.ID = fv.CustomFieldID
)
SELECT p.ID,
p.PersonName,
lvf.FieldValue AS Column1, --Bloodtype
lvf2.FieldValue as Column2 --EyeColour
FROM Person p
LEFT JOIN ListFieldValues lvf ON p.ID = lvf.PersonID and lvf.FieldOrderNumber =1
LEFT JOIN ListFieldValues lvf2 on p.ID = lvf2.PersonID and lvf2.FieldOrderNumber = 2
答案 0 :(得分:0)
首先,您需要在标识列上创建索引。然后在您要加入的列上创建索引。这些提示将缩短您的执行时间。