2015-01-01 21 views
-1

一個問題:兩個表 - 如何制定的加入

我有兩個表:

表站有列的stationID和全名。
表格路線具有列路線標識符,fromstationid,tostationid。

表格站具有保存的所有站的全名。每個電臺都有其唯一的ID(stationid是主鍵)。
表格路線具有所有路線信息。每條路線都有其唯一的ID(routeid是主鍵)和起始站(fromstationid)和終端站(tostationid)。

現在來自table station的stationid與stationid之間的fromstationid,tostationid與table station之間存在外鍵關係。

現在我想我的網站拼寫出以下信息:

Column 1: Route ID 
Column 2: Full name of the starting station 
Column 3: Full name of the terminal station 

我已經制定了兩個SQL查詢。

SELECT route.routeid, route.fromstationid, station.fullname 
FROM route INNER JOIN 
    station 
    ON route.fromstationid=station.stationid; 

SELECT route.routeid, route.tostationid, station.fullname 
FROM route INNER JOIN 
    station 
    ON route.totationid=station.stationid 

是否有任何使用一個SQL查詢(理想情況下在SQL數據庫中)完成此操作? 我錯過了一個重要的關係數據庫概念嗎?

回答

0

你非常接近。你只需要添加第二個連接到查詢,像這樣:

SELECT r.routeid, r.fromstationid, s1.fullname as start_station, r.tostationid, s2.fullname as end_station 
FROM route r 
LEFT JOIN station s1 ON r.fromstationid = s1.stationid 
LEFT JOIN station s2 ON r.tostationid = s2.stationid 
1

是的,你只需要加入到station兩次:

SELECT r.routeid, sfrom.fullname as fromstationname, sto.fullname as tostationname 
FROM route r INNER JOIN 
    station sfrom 
    ON r.fromstationid = sfrom.stationid INNER JOIN 
    station sto 
    ON r.totationid = sto.stationid