ForeignKey Referencing Same Table

后端 未结 5 1620
栀梦
栀梦 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:40

    I was assuming that foreign key would be linked with some other table as usual.

    It still is - it references other records in the same Person table.

    -- All Mothers
    SELECT mom.name
       FROM Person mom
       WHERE EXISTS (SELECT 1 FROM Person WHERE mother_id = mom.id);
    
    -- Children of John Smith and Jane
    SELECT kid.name
       FROM Person kid
       INNER JOIN Person mom on kid.mother_id = mom.id
       INNER JOIN Person dad on kid.father_id = dad.id
       WHERE mom.name = 'Jane' AND
       dad.name = 'John Smith';
    

    Have a look at this SQL fiddle here

提交回复
热议问题