mysql查询多个外键

时间:2018-09-03 10:44:25

标签: mysql database rdbms

mysql表如下


    +------------+----------------+----------------+
    | booking_id | boarding_point | dropping_point |
    +------------+----------------+----------------+
    |          1 |              2 |              4 |
    |          2 |              1 |              2 |
    +------------+----------------+----------------+


    +-------------+---------------+
    | location_id | location_name |
    +-------------+---------------+
    |           1 | chennai       |
    |           2 | coimbatore    |
    |           3 | tiruppur      |
    |           4 | erode         |
    |           5 | salem         |
    +-------------+---------------+

boarding_point和dropping_point是location_id的外键。 现在,我希望选择查询显示为


    +------------+----------------+----------------+
    | booking_id | boarding_point | dropping_point |
    +------------+----------------+----------------+
    |          1 |     coimbatore |          erode |
    |          2 |        chennai |     coimbatore |
    +------------+----------------+----------------+

任何人都可以建议我将查询显示为如上

1 个答案:

答案 0 :(得分:2)

将预订表两次加入位置表:

SELECT
    b.booking_id,
    t1.location_name,
    t2.location_name
FROM booking b
INNER JOIN location t1
    ON b.boarding_point = t1.location_id
INNER JOIN location t2
    ON b.dropping_point = t2.location_id;

enter image description here

Demo