2

我尝试使用多个从表中查询ORDER BY

SELECT TOP 50
  TBL_ContentsPage.NewsId,
  TBL_ContentsPage.author,
  TBL_ContentsPage.Header,
  TBL_ContentsPage.TextContent,
  TBL_ContentsPage.PostedDate,
  TBL_ContentsPage.status,
  TBLTempSettings.templateID
FROM TBL_ContentsPage
INNER JOIN TBLTempSettings
  ON TBL_ContentsPage.NewsId = TBLTempSettings.newsId
WHERE TBL_ContentsPage.mode = '1' AND TBLTempSettings.mode = '1' AND (TBLTempSettings.templateID = @templateID OR @templateID = 'all')
ORDER BY 0 + TBLTempSettings.rank DESC

但是当我添加TBL_ContentsPage.PostedDate DESC查询需要两倍以上的时间。TBLTempSettings.rank已经被索引。

4

2 回答 2

2

试试这个——

SELECT TOP 50   c.newsId
            ,   c.author
            ,   c.Header
            ,   c.TextContent
            ,   c.PostedDate
            ,   c.status
            ,   t.templateID
FROM TBL_ContentsPage c
JOIN (
    SELECT *
    FROM TBLTempSettings t
    WHERE t.mode = '1'
        AND (t.templateID = @templateID OR @templateID = 'all')
) t ON c.newsId = CAST(t.newsId AS INT)
WHERE c.mode = '1'
ORDER BY t.rank DESC
于 2013-09-25T07:15:07.817 回答
2

为了对查询结果进行排序,SQL Server 会消耗 CPU 时间。

ORDER BY 子句将所有查询结果尽快消耗到应用程序的内存中,然后进行排序。

您的应用程序已经设计为可以横向扩展多个应用程序服务器以分配 CPU 负载,而您的数据库服务器……不是。

排序操作除了使用 TEMPDB 系统数据库作为临时存储区域外,还为操作增加了很大的 I/O 率。

因此,如果您习惯在其查询中经常看到 Sort 运算符,并且该运算符的操作消耗很高,请考虑删除上述子句。另一方面,如果您知道这将始终按特定列组织您的查询,请考虑对其进行索引。

于 2013-09-25T07:15:15.020 回答