存储过程中两个表之间是否可以有多个连接?

Is it possible to have multiple joins between two tables in stored procedure?

我有两个 table,“预订”和“城市”。 CityName 字段是 City table 中的主键,我已将其用作 Booking table 中“SourceCity”和“DestinationCity”两列的外键。我想创建一个存储过程来 select 来自预订 table 的所有现有数据以创建视图列表,为此我编写了以下内容。

SELECT  [dbo].[Booking].[BookingID],
        [dbo].[Booking].[CustomerName],
        [dbo].[City].[CityName],
        [dbo].[City].[CityName],
        [dbo].[Booking].[StartingDate],
        [dbo].[Booking].[EndingDate],
        [dbo].[Car].[LicensePlateNumber],
        [dbo].[Driver].[DriverName],
        [dbo].[Booking].[AdvanceTaken],
        [dbo].[Booking].[PendingPayment],
        [dbo].[Booking].[TotalRent],
        [dbo].[Booking].[BookingDate],
        [dbo].[Booking].[IDProof]

FROM [dbo].[Booking]
**LEFT OUTER JOIN [dbo].[City]  
ON [dbo].[Booking].[SourceCity] = [dbo].[City].[CityName]
AND [dbo].[Booking].[DestinationCity] = [dbo].[City].[CityName]**
LEFT OUTER JOIN [dbo].[Driver]
ON [dbo].[Driver].[DriverID] = [dbo].[Booking].[DriverAllotted]
LEFT OUTER JOIN [dbo].[Car]
ON [dbo].[Car].[CarID] = [dbo].[Booking].[CarAllotted]
ORDER BY [dbo].[Booking].[BookingID]

我不确定是否可以执行以下操作

LEFT OUTER JOIN [dbo].[City]  
ON [dbo].[Booking].[SourceCity] = [dbo].[City].[CityName]
AND [dbo].[Booking].[DestinationCity] = [dbo].[City].[CityName]

我猜你需要一个不同的 JOIN

FROM [dbo].[Booking] as booking
LEFT OUTER JOIN [dbo].[City]  as source_city
ON booking.[SourceCity] = source_city.[CityName]
LEFT OUTER JOIN [dbo].[City]  as destination_city
ON booking.[DestinationCity] = destination_city.[CityName]

.....

是的,这是可能的,您只需要使用不同的 table alias。除了两次引用相同的 table 之外,table 别名可以使您的代码看起来更简洁,例如

SELECT  b.CustomerName,
        sc.CityName AS SourceCity,
        dc.CityName AS DestinationCity,
        b.StartingDate,
        b.EndingDate,
        c.LicensePlateNumber,
        d.DriverName,
        b.AdvanceTaken,
        b.PendingPayment,
        b.TotalRent,
        b.BookingDate,
        b.IDProof
FROM    dbo.Booking AS b
        LEFT OUTER JOIN dbo.City AS sc
            ON sc.CityName= b.SourceCity
        LEFT OUTER JOIN dbo.City AS dc  -- Different Alias here
            ON dc.CityName = b.DestinationCity
        LEFT OUTER JOIN dbo.Driver AS d
            ON d.DriverID = b.DriverAllotted
        LEFT OUTER JOIN dbo.Car AS c
            ON c.CarID = b.CarAllotted
ORDER BY
        b.BookingID;

我很欣赏 cleaner 有点主观,但如果有人发现这比您的原始查询更难阅读,我会感到惊讶