从SQL Server中的子查询获取多个列值将返回null

时间:2012-12-04 09:48:48

标签: tsql join subquery

我有以下查询:

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小时内,我一直陷入困境。

1 个答案:

答案 0 :(得分: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