ForeignKey Referencing Same Table

后端 未结 5 1621
栀梦
栀梦 2021-02-05 22:08

There was an interview test in which below was the table and structure

 Table Person = id, name, dob, dod, mother_id, father_id
 Primary Key (id)
 Foreign Key mo         


        
5条回答
  •  盖世英雄少女心
    2021-02-05 22:43

    You can always have foreign key that link to the same table.. There is not problem in that..

    See, suppose you are storing a person record in the table, now that person would be having mother and father. And mother and father both are themselves a person.. so, they are itself a record of the same table..

    Suppose you have following two records in Person table: -

    id     name           age         mother_id
    1      xyz            24          5
    5      abc            57          6
    

    So, from the above table you see that, person with id = 5 is actually mother of person with id = 1.. So, it is a foreign key referencing the same table..

    So, here rather than performing a join operation with a different table, you have to perform join with the same table..

    SELECT p2.id FROM
    Person p1 join Person p2
    WHERE p1.mother_id = p2.id
    

    This query will select the record of mother of your current record..

提交回复
热议问题