代码之家  ›  专栏  ›  技术社区  ›  Majid Fouladpour

mysql-同一表上的三个连接

  •  1
  • Majid Fouladpour  · 技术社区  · 14 年前

    我有两张桌子:

    persons
    - person_id
    - fullname
    
    students
    - student_id
    _ person_id
    - father_id
    - mother_id
    

    在students表中,最后三列存储persons表中的id。哪个SELECT可以检索以下数据:

    - student name
    - father name
    - mother name
    

    2 回复  |  直到 14 年前
        1
  •  4
  •   Pablo Santa Cruz    14 年前

    试试这个:

    select sp.fullname studentname, fp.fullname fathername, mp.fullname mothername
      from students s
     inner join persons sp on (s.student_id = sp.person_id)
     inner join persons fp on (s.father_id = fp.person_id)
     inner join persons mp on (s.mother_id = mp.person_id)
    
        2
  •  1
  •   Alpesh    14 年前

    尝试下面的查询-

    SELECT p.fullname,m.fullname,f.fullname from students s
        LEFT JOIN persons p ON s.person_id = p.id
        LEFT JOIN mother m ON s.mother_id = m.id
        LEFT JOIN father f ON s.father_id = f.id
        WHERE s.student_id = 'id of which student record you want';