MS SQL Order By要长时间执行

时间:2017-03-21 17:11:48

标签: sql sql-server

我在使用Order By执行SQL时遇到问题。 问题是,如果我在做Order By,需要很长时间,我的服务器上有一个峰值。 如果有任何方法可以通过

获取没有订单的最大值

具有排序依据的代码示例:

SELECT DISTINCT TOP 3 s.title, s.imageUrl, count(sv.saleid) as mostViewPeriod14Days, s.guid 
FROM dbo.Sales s 
INNER JOIN dbo.KEY_BrandcategoryToSale b_key ON s.id = b_key.saleId 
INNER JOIN dbo.SaleView sv ON s.id = sv.saleId 
WHERE (sv.date <= GETDATE()) 
AND (sv.date >= GETDATE() - 14) 
AND s.isActive = 1 AND s.isHotsale = 1 
AND b_key.brandCategoryId = 28 AND s.id NOT IN (SELECT sv.saleId FROM dbo.SaleView sv WHERE sv.userId = 99114) 
GROUP BY s.title, s.imageUrl, s.guid 
ORDER BY mostViewPeriod14Days Desc

我的工作是什么,但没有订单:

SELECT DISTINCT TOP 3 s.title, s.imageUrl, count(sv.saleid) as mostViewPeriod14Days, s.guid 
    FROM dbo.Sales s 
    INNER JOIN dbo.KEY_BrandcategoryToSale b_key ON s.id = b_key.saleId 
    INNER JOIN dbo.SaleView sv ON s.id = sv.saleId 
    WHERE (sv.date <= GETDATE()) 
    AND (sv.date >= GETDATE() - 14) 
    AND s.isActive = 1 AND s.isHotsale = 1 
    AND b_key.brandCategoryId = 28 AND s.id NOT IN (SELECT sv.saleId FROM dbo.SaleView sv WHERE sv.userId = 99114) 
    GROUP BY s.title, s.imageUrl, s.guid 

1 个答案:

答案 0 :(得分:1)

尝试以下查询,如果有帮助请告诉我。以下几点概述

  • 包含计算日期的WHERE子句比不包含计算日期的子句慢。
  • 如果可以避免,请不要在查询中添加“子选择”。将其更改为左连接并检查空记录(更快)

    var name = $("input#name").val();
    var email = $("input#email").val(); 
    var telephone = $("input#telephone").val();
    var message = $("textarea#message").val(); 
    
    var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&message=' + message;  
    
    $.ajax({  
      type: "POST",  
      url: "process.php",  
      data: dataString,  
    }  
    });