ForeignKey引用相同的表

ICo*_*sed 11 mysql sql

有一个面试测试,下面是表格和结构

 Table Person = id, name, dob, dod, mother_id, father_id
 Primary Key (id)
 Foreign Key mother_id references Person
 Foreign Key father_id references Person
Run Code Online (Sandbox Code Playgroud)

有人问道

  1. "选择所有母亲"
  2. "选择那些'约翰史密斯'和'简'的孩子

我很困惑,因为我假设外键会像往常一样与其他表联系起来.但那时我失败了.有人知道实际答案和原因吗?

pod*_*ska 15

这种数据结构称为"自引用表"

SELECT DISTINCT mothers.*
FROM person
    inner join person mothers on person.mother_id = mothers.id
Run Code Online (Sandbox Code Playgroud)

SELECT person.*
FROM person
    inner join person fathers on person.father_id = fathers.id
    inner join person mothers on person.mother_id = mothers.id
WHERE 
    fathers.name='john smith'
and 
    mothers.name='jane'
Run Code Online (Sandbox Code Playgroud)