2010-09-16 60 views
1

我有這個速度優化的查詢(這就是爲什麼它可能看起來有點奇怪 - 一段時間後得到一些幫助)。SQL查詢在哪裏問題

想要得到確切的結果,因爲這只是我只想從最後一分鐘內的結果不老。

此查詢返回最後的100個,不管是什麼,而不僅僅是最後一分鐘的結果。

SessionGuid不是唯一的 - 實際上它是這張表中多行中的一個鍵。

感謝您的幫助

SELECT TOP(@resultCount) * FROM 
( 
    SELECT 
     [UserSessionSequenceID] 
     ,[SessionGuid] 
     ,SiteID 
     ,IP 
     ,UrlTitle 
     ,Url 
     ,Referer 
     ,[Timestamp] 
     ,ROW_NUMBER() over (
      PARTITION BY [SessionGuid] 
      ORDER BY UserSessionSequenceID DESC) 
     AS sort 
    FROM [tblSequence] 
    where SiteID = @siteID 
    and [Timestamp] > DATEADD(mi, [email protected], (LEFT(GETDATE(),12))) 
) AS new 
WHERE sort = 1 
and not exists (
    select SessionGuid 
    from tblSequence 
    where SiteID = @siteID 
    and SessionGuid = new.SessionGuid 
    and [TimeStamp] < DATEADD(mi, [email protected], (LEFT(GETDATE(),12))) 
) 
ORDER BY [UserSessionSequenceID] DESC 

我的表看起來像這樣

CREATE TABLE [dbo].[tblSequence](
    [UserSessionSequenceID] [bigint] IDENTITY(1,1) NOT NULL, 
    [IP] [nvarchar](50) NULL, 
    [SessionGuid] [nvarchar](50) NOT NULL, 
    [Url] [nvarchar](1550) NULL, 
    [UrlTitle] [nvarchar](1550) NULL, 
    [Cords] [nvarchar](2550) NULL, 
    [SiteID] [int] NOT NULL, 
    [BrowserWidth] [int] NULL, 
    [BrowserHeight] [int] NULL, 
    [Browser] [nvarchar](550) NULL, 
    [BrowserVersion] [nvarchar](50) NULL, 
    [IsCrawler] [bit] NOT NULL, 
    [Referer] [nvarchar](1550) NULL, 
    [Timestamp] [datetime] NULL 
) ON [PRIMARY] 

回答

3

我把你的問題重新編寫爲:

WITH new AS (
    SELECT [UserSessionSequenceID], 
      [SessionGuid], 
      SiteID, 
      IP, 
      UrlTitle, 
      Url, 
      Referer, 
      [Timestamp], 
      ROW_NUMBER() OVER (PARTITION BY [SessionGuid] 
           ORDER BY UserSessionSequenceID DESC) AS sort 
    FROM [tblSequence] 
    WHERE SiteID = @siteID 
     AND [Timestamp] > DATEADD(mi, [email protected], GETDATE())) 
    SELECT TOP(@resultCount) 
     n.* 
    FROM new n 
    WHERE n.sort = 1 
    AND NOT EXISTS (SELECT NULL 
        FROM tblSequence s 
        WHERE s.siteid = n.siteid 
         AND s.sessionguid = n.sessionguid 
         AND [TimeStamp] <= DATEADD(mi, [email protected], GETDATE()) 
ORDER BY n.usersessionsequenceid DESC