0

有没有办法在没有子查询的情况下重写这个 SP。基本上 I.RemarkId 有时可以为空,我试图使用左连接或左外连接。我想始终从 flightinfo 返回行,并在 I.RemarkId 不为空时返回备注,并且在 I.remarkId 为空时在备注列中返回备注。

ALTER PROCEDURE [dbo].[Peach_GetFlightInfoForRoute]
    @FlightDate datetime,   
    @Origin nvarchar(3),
    @dest nvarchar(3),
    @Lang nvarchar(2)
AS
SELECT 
     I.FlightNumber
    ,FlightDate
    ,STD
    ,(select [Message] FROM FlightRemarkDetail WHERE RemarkId = I.RemarkId WHERE LangCode = @Lang) As [Remark]
FROM 
     [FlightInfo] as [I]
JOIN
     [FlightNumbers] as [N]
ON  
    I.FlightNumber = N.FlightNumber 
WHERE 
    FlightDate = @FlightDate AND (@Origin='' OR @Origin = N.Origin) AND (@dest = '' OR @dest = N.Destination)

FlightInfo
===========
FlightNumber    nvarchar(16)
FlightDate  datetime    
STD nvarchar(4) 
RemarkId int NULL

FlightRemarkDetail
==================
RemarkDetailId  int 
RemarkId    int NOT NULL
LangCode    nvarchar(2) 
Message nvarchar(512)   
4

1 回答 1

1

LEFT OUTER JOIN本质上是一样的。 LEFT OUTER JOIN使它不需要子表具有匹配的记录。因此,如果 FlightRemarkDetail 中没有记录,它将简单地显示为空(类似于您从子查询中获得的结果)。这是假设 FlightInfo 和 FlightRemarkDetail 之间存在 1 对 1(或 1 对 0)匹配。如果每个 FlightInfo 存在多个 FlightRemarkDetail 记录,则会导致重复行。

SELECT 
     I.FlightNumber
    ,FlightDate
    ,STD
    ,D.Message As [Remark]
FROM 
     [FlightInfo] as [I]
JOIN [FlightNumbers] as [N] ON I.FlightNumber = N.FlightNumber 
LEFT OUTER JOIN [FlightRemarkDetail] as [D] ON I.RemarkId = D.RemarkId
WHERE 
    FlightDate = @FlightDate AND (@Origin='' OR @Origin = N.Origin) AND (@dest = '' OR @dest = N.Destination)
于 2012-10-03T05:35:45.403 回答