加入两个mysql查询

时间:2013-05-23 08:33:43

标签: mysql sql join

我有3张桌子:

表1

RouteID             int
departure_stop      int 
destination_stop    int 
Price               decimal(6,2) 

表2

StopID          int
Stop            varchar(50)
Cities_CityID   int

表3

CityID      int
City        varchar(50)     

我希望得到比50便宜的所有路线。 我想要像这样离开城市和目的地城市

City    City
Paris   London
Madrid  Zagred

到目前为止,我有两个问题,我正在离开城市,然后第二次查询目的地城市,但不知道如何并排加入他们。以下是我的疑问:

SELECT
    Cities.City
FROM Routes, Stops, Cities
WHERE (Stops.StopID = Routes.departure_stop AND Stops.Cities_CityID = Cities.CityID AND Routes.price < '50') 

SELECT
    Cities.City
FROM Routes, Stops, Cities
WHERE (Stops.StopID = Routes.destination_stop AND Stops.Cities_CityID = Cities.CityID AND Routes.price < '50')

所以问题是如何将它们并排在一起,这样我才能看到出发地和目的地?

1 个答案:

答案 0 :(得分:0)

Select
    DepartureCity.City AS 'Departure City',
    DestinationCity.City AS 'Destination City'
FROM Routes
INNER JOIN Stops DepartureStop    ON DepartureStop.StopID   = Routes.departure_stop
INNER JOIN Stops DestinationStop  ON DestinationStop.StopID = Routes.destination_stop 
INNER JOIN Cities DepartureCity   ON DepartureCity.CityID   = DepartureStop.Cities_CityID 
INNER JOIN Cities DestinationCity ON DepartureCity.CityID   = DestinationStop.Cities_CityID 

WHERE Routes.price < 50