查询花费太多时间来加载数据

时间:2018-04-13 05:28:22

标签: sql-server stored-procedures inner-join

我从一组带连接的表中选择数据,但是当我执行它时,它花费了太多时间。 applicationusagelog表包含批量数据。

   SELECT  CONVERT(varchar(6),( AccessTime/3600))
            + ':' + RIGHT('0' + CONVERT(varchar(2), (AccessTime % 3600) / 60), 2)
            + ':' + RIGHT('0' + CONVERT(varchar(2), AccessTime % 60), 2) as AccessTime
            From
            (
                Select SUM(DATEPART(SECOND,LogTime)) as AccessTime
                From   applicationusagelog
                       Inner Join usermaster    On usermaster.EmployeeID=applicationusagelog.CreatedBy
                       Inner Join em_masteruser On em_masteruser.id=usermaster.OrganizationId
                Where  Cast(applicationusagelog.CreatedOn as date) Between '01-01-2018' And '04-04-2018' 
                And    em_masteruser.id='1' 
                And    applicationusagelog.ApplicationName not in
                        (
                            SELECT  master_domainapp.domainname 
                            From    master_domainapp
                                    Inner Join master_category_application On master_category_application.CategoryId=master_domainapp.CategoryId
                                    Inner Join em_masteruser On em_masteruser.id=master_domainapp.CreatedBy
                            Where  em_masteruser.id='1' 
                            And    master_category_application.CreatedBy='1'
                        )
            )x
有人帮助减少加载时间...

2 个答案:

答案 0 :(得分:0)

很可能在where子句中将createdon强制转换为datetime是罪魁祸首。使用强制转换后,数据库不能再使用索引来减少设置为您的日期范围的潜在结果集。这反过来迫使数据库查看整个日期范围,这反过来会导致很多非常慢的磁盘访问。

您应该将createdon的字段类型更改为日期格式(如datetime)并编写查询而不进行强制转换。如果之后仍然很慢,请在createdon字段上放置一个索引。

答案 1 :(得分:0)

尝试使用NOT IN更改LEFT JOIN条件。

SELECT DISTINCT master_domainapp.domainname
INTO #domainnames
FROM master_domainapp
INNER JOIN master_category_application ON master_category_application.CategoryId = master_domainapp.CategoryId
INNER JOIN em_masteruser ON em_masteruser.id = master_domainapp.CreatedBy
WHERE em_masteruser.id = '1'
    AND master_category_application.CreatedBy = '1'

SELECT CONVERT(VARCHAR(6), (AccessTime / 3600)) + ':' + RIGHT('0' + CONVERT(VARCHAR(2), (AccessTime % 3600) / 60), 2) + ':' + RIGHT('0' + CONVERT(VARCHAR(2), AccessTime % 60), 2) AS AccessTime
FROM (
    SELECT SUM(DATEPART(SECOND, LogTime)) AS AccessTime
    FROM applicationusagelog
    INNER JOIN usermaster ON usermaster.EmployeeID = applicationusagelog.CreatedBy
    INNER JOIN em_masteruser ON em_masteruser.id = usermaster.OrganizationId
    LEFT JOIN #domainnames ON #domainnames.domainname = applicationusagelog.ApplicationName
    WHERE Cast(applicationusagelog.CreatedOn AS DATE) BETWEEN '01-01-2018'
            AND '04-04-2018'
        AND em_masteruser.id = '1'
        AND #domainnames.domainname IS NULL
    ) x

如果NOT IN子查询中的表很重,这可能会提高性能。