使用多个外键将MySQL中的表连接起来

时间:2014-10-20 22:49:51

标签: mysql sql

我有2张桌子

骑行(从一个点到另一个点)

+------+-------+-------+-------+-------+
| id   | start | end   | pointA| pointB|
+------+-------+-------+-------+-------+
| 1    | xxx   |    xx |    1  |    2  |
| 2    | xxx   |    xx |    2  |    1  |
+------+-------+-------+-------+-------+

+------+-------------+
| id   | desc        |
+------+-------------+
| 1    | "Chicago"   |    
| 2    | "NYC"       |    
+------+-------------+

例如:

当一个人从A点骑到B点时,它会被记录在rides表中。 pointApointB都是表rides

points表格中的FK

如何以MySQL的方式获取id = 1的SQL输出,例如+------+-------+-------+-------+-------+ | id | start | end | pointA| pointB| +------+-------+-------+-------+-------+ | 1 | xxx | xx |Chicago| NYC |

{{1}}

1 个答案:

答案 0 :(得分:1)

您可以通过为每个表添加不同的别名来连接同一个表:

SELECT r.id, r.start, r.end, pA.desc as pointA, pB.desc as pointB
FROM rides r
JOIN points pA ON pA.id = r.pointA
JOIN points pB ON pB.id = r.pointB
WHERE r.id = 1;