左外连接查询非常慢 - SQL Server

时间:2016-08-29 15:17:58

标签: sql sql-server database performance join

SQL Server查询的巨大问题!

因此下面的查询在查询中使用了JOIN命令,但运行时间不少于15-20分钟!不知道如何更好地优化此代码:(

有关如何解决此问题的任何想法?

SELECT dbo.DB_Timetrack.[JOB #], dbo.DB_Timetrack.[Last Name], dbo.DB_Timetrack.[First Name], dbo.DB_Timetrack.HOURS, dbo.DB_Timetrack.BEGDATE, dbo.DB_Timetrack.LOCATNID, 
                         dbo.DB_Timetrack.DESCR, dbo.DB_Timetrack.CODE, dbo.DB_Timetrack.TYPE, 
                         CASE WHEN dbo.DB_Job_status_open_and_closed.WS_Job_Number != '' THEN dbo.DB_Timetrack.Hours ELSE 0 END AS HoursWon, dbo.DB_Timetrack.NUMBERONLY, 
                         dbo.DB_Job_status_open_and_closed.WS_Job_Number_Only, dbo.DB_Job_status_open_and_closed.CREATDDT, DATEDIFF(Day, dbo.DB_Timetrack.BEGDATE, 
                         dbo.DB_Job_status_open_and_closed.CREATDDT) AS Date_Difference, DBCRM_MSCRM.dbo.DB_Opportunity_SalespersonID.new_GPSalespersonName, 
                         CASE WHEN DBCRM_MSCRM.dbo.DB_Opportunity_SalespersonID.new_GPSalesRepCode <> '' THEN DBCRM_MSCRM.dbo.DB_Opportunity_SalespersonID.new_GPSalesRepCode ELSE dbo.DB_Job_status_open_and_closed.Salesperson
                          COLLATE Latin1_General_CI_AI END AS SalespersonID

FROM            dbo.DB_Timetrack LEFT OUTER JOIN
                         DBCRM_MSCRM.dbo.DB_Opportunity_SalespersonID ON dbo.DB_Timetrack.NUMBERONLY COLLATE Latin1_General_CI_AI = DBCRM_MSCRM.dbo.DB_Opportunity_SalespersonID.Job_Num_Only LEFT OUTER JOIN
                         dbo.DB_Job_status_open_and_closed ON dbo.DB_Timetrack.NUMBERONLY = dbo.DB_Job_status_open_and_closed.WS_Job_Number_Only

WHERE        (dbo.DB_Timetrack.HOURS > 0) AND (dbo.DB_Timetrack.DESCR <> '') AND (dbo.DB_Timetrack.BEGDATE > CONVERT(DATETIME, '2013-01-01 00:00:00', 102))

任何建议都将不胜感激!

1 个答案:

答案 0 :(得分:2)

这基本上是您的查询:

SELECT . . .
FROM dbo.DB_Timetrack LEFT OUTER JOIN
     DBCRM_MSCRM.dbo.DB_Opportunity_SalespersonID
     ON dbo.DB_Timetrack.NUMBERONLY COLLATE Latin1_General_CI_AI = DBCRM_MSCRM.dbo.DB_Opportunity_SalespersonID.Job_Num_Only LEFT OUTER JOIN
     dbo.DB_Job_status_open_and_closed
     ON dbo.DB_Timetrack.NUMBERONLY = dbo.DB_Job_status_open_and_closed.WS_Job_Number_Only
WHERE (dbo.DB_Timetrack.HOURS > 0) AND
      (dbo.DB_Timetrack.DESCR <> '') AND
      (dbo.DB_Timetrack.BEGDATE > CONVERT(DATETIME, '2013-01-01 00:00:00', 102))

1。)首先,collat​​ion语句可能会终止任何索引的使用。

2。)您需要确保在DB_Job_status_open_and_closed(WS_Job_Number_Only)DB_Opportunity_SalespersonID(Job_Num_Only)上有索引。

3.。)您可能还会发现DB_Timetrack(BEGDATE, HOURS, DESCR, NumberOnly)上的索引有用(如果您确实使用的是SQL Server,则最后三列可能只是include。)