我有它運行的SQL Server CE下面的SQL查詢4如何解決SQL Server上的這個查詢性能精簡版4
SELECT [Join_ReleaseMinDatePost].[FK_MovieID]
FROM (
SELECT [FK_MovieID], MIN([DatePost]) AS [ReleaseMinDatePost]
FROM [Release]
GROUP BY [FK_MovieID]
) [Join_ReleaseMinDatePost]
INNER JOIN
(
SELECT COUNT([ID]) AS [FolderCount], [FK_MovieID]
FROM [MovieFolder]
GROUP BY [FK_MovieID]
) [Join_MovieFolder]
ON [Join_MovieFolder].[FK_MovieID] = [Join_ReleaseMinDatePost].[FK_MovieID]
此查詢需要很長的時間來執行,但如果我改變部分
SELECT COUNT([ID]) AS [FolderCount], [FK_MovieID] FROM [MovieFolder] GROUP BY [FK_MovieID]
要
SELECT 1 AS [FolderCount], [FK_MovieID] FROM [MovieFolder]
所以,完整的查詢變得
SELECT [Join_ReleaseMinDatePost].[FK_MovieID]
FROM (SELECT [FK_MovieID], MIN([DatePost]) AS [ReleaseMinDatePost] FROM [Release] GROUP BY [FK_MovieID]) [Join_ReleaseMinDatePost]
INNER JOIN (SELECT 1 AS [FolderCount], [FK_MovieID] FROM [MovieFolder]) [Join_MovieFolder]
ON [Join_MovieFolder].[FK_MovieID] = [Join_ReleaseMinDatePost].[FK_MovieID]
然後表現變得非常快。
問題是,如果自己拿的部分是相當快的變化。但出於某種原因,第一個查詢的執行計劃顯示索引掃描中的「實際行數」爲160,016,而表格MovieFolder中的總行數爲2,192。 和「估計的行數」是2,192。
所以我認爲問題是在行數,但我無法弄清楚爲什麼它的一切搞砸了。
任何幫助將不勝感激:) 感謝
表的模式如下
CREATE TABLE [Release] (
[ID] int NOT NULL
, [FD_ForumID] int NOT NULL
, [FK_MovieID] int NULL
, [DatePost] datetime NULL
);
GO
ALTER TABLE [Release] ADD CONSTRAINT [PK__Release__0000000000000052] PRIMARY KEY ([ID]);
GO
CREATE INDEX [IX_Release_DatePost] ON [Release] ([DatePost] ASC);
GO
CREATE INDEX [IX_Release_FD_ForumID] ON [Release] ([FD_ForumID] ASC);
GO
CREATE INDEX [IX_Release_FK_MovieID] ON [Release] ([FK_MovieID] ASC);
GO
CREATE UNIQUE INDEX [UQ__Release__0000000000000057] ON [Release] ([ID] ASC);
GO
CREATE TABLE [MovieFolder] (
[ID] int NOT NULL IDENTITY (1,1)
, [Path] nvarchar(500) NOT NULL
, [FK_MovieID] int NULL
, [Seen] bit NULL
);
GO
ALTER TABLE [MovieFolder] ADD CONSTRAINT [PK_MovieFolder] PRIMARY KEY ([ID]);
GO
CREATE INDEX [IX_MovieFolder_FK_MovieID] ON [MovieFolder] ([FK_MovieID] ASC);
GO
CREATE INDEX [IX_MovieFolder_Seen] ON [MovieFolder] ([Seen] ASC);
GO
CREATE UNIQUE INDEX [UQ__MovieFolder__0000000000000019] ON [MovieFolder] ([ID] ASC);
GO
CREATE UNIQUE INDEX [UQ__MovieFolder__0000000000000020] ON [MovieFolder] ([Path] ASC);
GO
查詢的目的是什麼?爲什麼你需要內部加入每部電影的計數列表,當你不使用計數的任何東西? – Alex
這是一個更大的查詢的一部分,但我孤立的部分,使放緩,並把它放在這裏,所以它可能讓其他人unerstand它:) – Karim
你可以改變SELECT爲「SELECT [Join_ReleaseMinDatePost]。[FK_MovieID],[ReleaseMinDatePost],[FOLDERCOUNT]」所以它更有意義:) – Karim