简体   繁体   中英

Joining tables in MySQL with multiple foreign keys

I have 2 tables

Rides (from one point to another)

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

Points

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

So for example:

When a person rides from point A to point B it gets registerd in the rides table. pointA and pointB are both FK's in the rides table from the table points

How is it possible to get an SQL output in MySQL like this for a ride where id = 1 for example:

+------+-------+-------+-------+-------+
| id   | start | end   | pointA| pointB|
+------+-------+-------+-------+-------+
| 1    | xxx   |    xx |Chicago|  NYC  |

You can join the same table twice, by giving each one a different alias:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM