优化数据库查询运行速度越来越快,记录数越来越多

时间:2015-07-16 16:03:21

标签: sql database

是否有更好的方法来优化此查询,随着更多记录添加到数据库,它会越来越慢。

由于

 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "dailyLimitExceededUnreg",
    "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
    "extendedHelp": "https://code.google.com/apis/console"
   }
  ],
  "code": 403,
  "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
 }
}

SQL Server 2012

表定义enter image description here

SELECT     
    VoterID, AnswerID, SectionNumber, AnswerText, SurveyID, 
    CaseID, versionID, voterAnswerStatus, dateupdated, 
    recordstatus, modifiedby
FROM         
    Sample.vts_tbVoterAnswers AS a
WHERE
    (dateupdated = (SELECT MAX(dateupdated) AS Expr1
                    FROM Sample.vts_tbVoterAnswers AS b
                    WHERE (a.VoterID = VoterID) 
                      AND (a.AnswerID = AnswerID) 
                      AND (a.SectionNumber = SectionNumber) 
                      AND (a.SurveyID = SurveyID) 
                      AND (a.CaseID = CaseID) 
                      AND (a.versionID = versionID)))
    AND (recordstatus <> 'D')

希望这有帮助

以下是与查询相关联的索引。

    [Sample].[vts_tbVoterAnswers](
[VoterAnswerID_PK] [int] IDENTITY(1,1) NOT NULL,
[VoterID] [int] NOT NULL,
[AnswerID] [int] NOT NULL,
[SectionNumber] [int] NOT NULL,
[AnswerText] [ntext] NULL,
[SurveyID] [int] NULL,
[CaseID] [int] NULL,
[versionID] [int] NULL,
[voterAnswerStatus] [varchar](20) NULL,
[dateupdated] [datetime] NOT NULL,
[recordstatus] [varchar](2) NULL,
[modifiedby] [varchar](40) NULL,
[changereason] [varchar](200) NULL,
 CONSTRAINT [PK_vts_tbVoterAnswers] PRIMARY KEY CLUSTERED 
(
    [VoterAnswerID_PK] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

enter image description here

3 个答案:

答案 0 :(得分:1)

尝试重写为RANK并查看是否有帮助:

SELECT     
    VoterID, AnswerID, SectionNumber, AnswerText, SurveyID, 
    CaseID, versionID, voterAnswerStatus, dateupdated, 
    recordstatus, modifiedby
FROM
 (
  SELECT     
    VoterID, AnswerID, SectionNumber, AnswerText, SurveyID, 
    CaseID, versionID, voterAnswerStatus, dateupdated, 
    recordstatus, modifiedby,
    RANK() OVER (PARTITION BY VoterID, AnswerID, SectionNumber, SurveyID, CaseID, versionID ORDER BY dateupdated DESC) AS rnk
  FROM         
     Sample.vts_tbVoterAnswers AS a
 ) AS dt
WHERE (recordstatus <> 'D')
  AND rn = 1

答案 1 :(得分:0)

我在DateUpdated上看不到索引。没有它,数据库必须遍历整个表,以查找与DateUpdated=(... subquery ...)匹配的行。在单个DateUpdated列上添加索引。

答案 2 :(得分:0)

使用FISRT_VALUE OVER PARTITIONsee documentation)代替子查询。

对于未用作分区键的每一列,它应该类似于以下代码:

FIRST_VALUE(columnname)
  OVER (
    PARTITION BY VoterID, AnswerID, SectionNumber, SurveyID, CaseID, versionID
    ORDER BY dateupdated ASC
  ) AS columnname