【问题标题】:mysql - three joins on the same tablemysql - 同一张表上的三个连接
【发布时间】:2010-10-24 12:43:07
【问题描述】:

我有两张桌子:

persons
- person_id
- fullname

students
- student_id
_ person_id
- father_id
- mother_id

在学生表中,最后三列存储人员表中的 ID。什么 SELECT 可以检索以下数据:

- student name
- father name
- mother name

为简单起见,我们假设没有 WHERE、ORDER BY 或 LIMIT

【问题讨论】:

    标签: sql mysql


    【解决方案1】:

    试试这个:

    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】:

      试试下面的查询 -

      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';
      

      【讨论】:

      • 谢谢,但是这样一来,返回的记录集中的字段不都是fullname吗?
      猜你喜欢
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      • 2015-05-18
      • 2015-07-24
      • 2014-05-08
      相关资源
      最近更新 更多