如何加入选择语句

时间:2018-12-26 15:17:02

标签: sql-server

请注意,DepartCountryIDArrivalCountryIDTravelCountryID的两个外键

CREATE TABLE [dbo].[Airlines]
(
    [AirlineID] [bigint] IDENTITY(1,1) NOT NULL,
    [CompanyID] [int] NOT NULL,
    [Code] [nvarchar](50) NOT NULL,
    [DepartCountryID] [bigint] NOT NULL,
    [ArrivalCountryID] [bigint] NOT NULL,
    [DepartTime] [datetime] NOT NULL,
    [ArrivalTime] [datetime] NOT NULL,

CREATE TABLE [dbo].[TravelCountries]
(
    [TravelCountryID] [bigint] NOT NULL,
    [CountryName] [nvarchar](50) NOT NULL,

这是第一个选择查询:

SELECT 
    [Code], [DepartTime], [ArrivalTime], [CountryName] AS DepartCountry  
FROM 
    [Airlines], [TravelCountries] 
WHERE 
    [DepartCountryID] = [TravelCountryID])

结果:

1X2VC   2017-01-01 00:00:00.000 2017-01-01 03:30:00.000 Andorra
3VGH23  2018-01-10 18:45:00.000 2018-01-15 04:30:00.000 USA

第二个选择查询:

SELECT 
    [Code], [DepartTime], [ArrivalTime], [CountryName] AS ArrivalCountry
FROM 
    [Airlines], [TravelCountries]
WHERE 
    [ArrivalCountryID] = [TravelCountryID])

结果:

1X2VC   2017-01-01 00:00:00.000 2017-01-01 03:30:00.000 France
3VGH23  2018-01-10 18:45:00.000 2018-01-15 04:30:00.000 England

我希望结果是:

1X2VC   2017-01-01 00:00:00.000 2017-01-01 03:30:00.000 Andorra France
3VGH23  2018-01-10 18:45:00.000 2018-01-15 04:30:00.000 USA     England

1 个答案:

答案 0 :(得分:2)

由于未提供表中的数据,因此我无法检查建议的解决方案,但它应该可以工作。 因此,如Shidersz在评论中所述,您应该使用JOINS(推荐使用LEFT JOIN以确保显示所有航空公司),并为表指定别名,因为您需要两次使用同一表:

SELECT  [Airlines].[Code],
        [Airlines].[DepartTime],
        [Airlines].[ArrivalTime],
        TravelCountryDepart.[CountryName] as CountryDeparture,
        TravelCountryArrival.[CountryName] as CountryArrival 
FROM [Airlines]
LEFT JOIN [TravelCountries] TravelCountryDepart
    ON [Airlines].[DepartCountryID] = TravelCountryDepart.[TravelCountryID] 
LEFT JOIN [TravelCountries] TravelCountryArrival
    ON [Airlines].[ArrivalCountryID] = TravelCountryArrival.[TravelCountryID]