mysql - 同一个表上的三个连接

时间:2010-10-24 12:43:07

标签: sql mysql

我有两张桌子:

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

2 个答案:

答案 0 :(得分:4)

试试这个:

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)

答案 1 :(得分:1)

尝试以下查询 -

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