两个表 - 如何制定连接

时间:2015-01-01 23:49:35

标签: php mysql join key

一个问题:

我有两张桌子:

表站的列号为stationid和fullname 表路由的列为routeid,fromstationid,tostationid。

表站具有已保存的所有站的全名。每个站都有其唯一的ID(stationid是主键) 表路由包含所有路由信息。每条路由都有唯一的ID(routeid是主键)和起始站(fromstationid)和终端站(tostationid)。

现在来自表路径的fromstationid,tostationid与来自表站的stationid之间存在外键关系。

现在我希望我的网站拼出以下信息:

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数据库上)完成此操作? 我错过了一个重要的关系数据库概念吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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