新手SQL编写者在这里试图更好地理解调度和高效的代码编写。我正在运行一个表现非常差的查询,我不明白为什么。我们正在使用SQL Server 2012。
当我只运行子查询(别名为“te”)时,它在不到一秒的时间内运行并返回零行(我预期的那样)。但是当我运行完整的查询时,它需要花费一分钟的时间。内部联接或左外部联接是否始终返回空集?所以,当子查询没有返回任何结果时,数据库引擎是否应该确定它不需要执行任何这些连接?
有关如何更好地优化的任何建议?在将来编写SQL时,我应该记住哪些最佳实践?
INSERT INTO #target_events
SELECT p.polyname,
bp.PurposeAbbr,
s.schid,
s.ldate,
es.EvStrId,
es.evstrname,
e.evparent,
e.evid,
e.Lat / 1000000.0 AS 'Lat',
e.Lon / 1000000.0 AS 'Lon',
e.eta,
e.etd,
e.PassOn,
e.PassOnBoard,
e.Activity,
e.SchedStatus,
e.EvClass
FROM
(
SELECT te.*
FROM #target_events te
LEFT OUTER JOIN #target_events te2 ON te2.schid = te.schid
AND te2.EvStrId = te.EvStrId
AND te2.EvParent = te.EvParent
AND te2.Activity != te.Activity
WHERE te.Activity IN(0, 1)
AND te.SchedStatus = 3
AND te2.EvId IS NULL
) te -- This subquery runs in under 1 second and returns zero rows
INNER JOIN events e ON e.schid = te.schid
AND e.EvStrId = te.EvStrId
AND e.EvParent = te.EvParent
AND e.Activity != te.Activity
INNER JOIN eventstrings es ON es.evstrid = e.evstrid
AND es.schid = e.schid
INNER JOIN schedules s ON s.schid = e.schid
LEFT OUTER JOIN clients c ON c.clientid = e.clientid
LEFT OUTER JOIN address a ON a.addrid = c.clientid
AND a.AddrType = 'CH' -- Client Home addresses.
LEFT OUTER JOIN polygons p ON p.polyid = a.jurispolyid
LEFT OUTER JOIN booking b ON b.bookingid = e.bookingid
LEFT OUTER JOIN bookingpurpose bp ON bp.purposeid = b.purposeid; -- These joins take a long time...