显示外键所指的内容

时间:2018-03-16 16:15:39

标签: mysql

                   **Student Table**
            ---------------------------------
            id    name  address placeofbirth
            ---------------------------------
            1     Kim     1          2
            2     ahmed   3          4
            3     john    1          3

                **City Table**
            ---------------------------------
                id    name
            ---------------------------------
                1     New York
                2     Boston
                3     Denver
                4     Washington


                **Result**
            -----------------------------------------
            Student        address      Placeofbirth
            -----------------------------------------
            Kim            New York        Boston
            ahmed          Denver          Washington
            John           New York        Denver

我没有连接它们的桥接表,请帮助我如何实现所需的结果,我使用的是mysql和c#

2 个答案:

答案 0 :(得分:2)

你有出生地..与城市id匹配..这是结果和地址的关系,这也是另一种关系

因此您只需加入与您的城市表相关的列

select s.student, a.name address, b.name Placeofbirth
from Student s 
inner join City a on a.id = s.address 
inner join City b on b.id = s.Placeofbirth 

两次fk ..两次加入

答案 1 :(得分:1)

SELECT s.name as Student, a.name AS address, p.name AS Placeofbirth 
FROM Student s
INNER JOIN City a ON s.address = a.id
INNER JOIN City p ON s.placeofbirth = p.id;

详细了解JOIN here