我想知道是否有處理下列情況更快,更好的方式:優化左加入大量數據的選擇查詢的SQL
我現在發現自己努力優化一個漫長的選擇的執行時間查詢,我需要爲每個記錄的每個唯一字段進行左連接(基本上旋轉表)。是否有一種方法可以通過單個連接/數據透視將其最小化,以減少檢索數據所需的時間?
我需要作出規定,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
您需要在要加入的列上添加索引。另外,請用您正在使用的DBMS標記問題:MySQL,SQL-Server,Oracle等。 – Barmar
我已經在相關表的DB上使用了索引。 – user3752234
您發佈了CREATE TABLE語句,但沒有提及任何索引。發佈索引創建語句,以便我們可以看到是否有正確的索引創建語句。 – Barmar