0

我有以下查询:

SELECT p.IdS, 
       p.PID, 
       a.Destination, 
       d.DelDate, 
       d.DelTimeE, 
       d.DelTimeL,
       td.EDateTime, 
       td.ECode, 
       td.[Source]
FROM Parcel p
LEFT JOIN Party a ON p.IdS = a.IdS
LEFT JOIN DateAndTime d ON p.IdS = d.IdS
LEFT OUTER JOIN 
(SELECT TOP(1) PID, 
               EDateTime, 
               ECode, 
               [Source] 
               FROM TgData 
               WHERE ECode='I' ORDER BY ID ASC) AS td
ON p.PID = td.PID
LEFT JOIN Ships s ON p.IdS = s.ShipId
WHERE s.IsFinalized='1' AND s.DComplete='2012-11-30' AND DelDate IS NOT NULL
ORDER BY Destination ASC

但是对于某些人来说,出于我未知的原因,即使我知道应该在那里显示一些值,数据库响应中的 td 列总是“NULL”。查询在 < 1 秒内执行

我还尝试了另一种方式来做到这一点:

        SELECT p.IdS, 
           p.PID, 
           a.Destination, 
           d.DelDate, 
           d.DelTimeE, 
           d.DelTimeL,
       (SELECT TOP(1) EDateTime FROM TgData WHERE ECode='I' AND PID=p.PID ORDER BY ID ASC) AS EDateTime
       (SELECT TOP(1) ECode FROM TgData WHERE ECode='I' AND PID=p.PID ORDER BY ID ASC) AS ECode
       (SELECT TOP(1) [Source] FROM TgData WHERE ECode='I' AND PID=p.PID ORDER BY ID ASC) AS [Source]
FROM Parcel p
LEFT JOIN Party a ON p.IdS = a.IdS
LEFT JOIN DateAndTime d ON p.IdS = d.IdS
LEFT JOIN Ships s ON p.IdS = s.ShipId
WHERE s.IsFinalized='1' AND s.DComplete='2012-11-30' AND DelDate IS NOT NULL
ORDER BY Destination ASC

这将获得正确的数据,但查询需要 20 秒才能显示 470 行。:P

任何提示或提示都会很可爱,在过去的 24 小时里,我一直在思考这个问题。

4

1 回答 1

0

试试这个查询

SELECT 
    p.IdS, 
    p.PID, 
    a.Destination, 
    d.DelDate, 
    d.DelTimeE, 
    d.DelTimeL,
    EDT.EDateTime AS EDateTime,
    EC.ECode AS ECode,
    TDL.Source as Source
FROM Parcel p
LEFT JOIN Party a ON p.IdS = a.IdS
LEFT JOIN DateAndTime d ON p.IdS = d.IdS
LEFT JOIN Ships s ON p.IdS = s.ShipId
LEFT JOIN (SELECT PID , TOP(1) EDateTime FROM TgData WHERE ECode='I') as EDT ON EDT.PID = p.PID
LEFT JOIN (SELECT PID , TOP(1) ECode FROM TgData WHERE ECode='I') AS EC ON EC.PID=p.PID
LEFT JOIN (SELECT PID , TOP(1) Source FROM TgData WHERE ECode='I') AS TDL ON TDL.PID=p.PID
WHERE s.IsFinalized='1' 
    AND s.DComplete='2012-11-30' 
    AND DelDate IS NOT NULL
ORDER BY Destination ASC
于 2012-12-04T09:59:34.867 回答