加入三个表与父子关系

时间:2017-03-19 14:58:43

标签: mysql sql join

假设我们在以下结构中有四个表(表名 - 字段):

person - id, name
doctor - id_person, specialty
pacient - id_person, disease
appointment - doctor_id, pacient_id, date

如何构建查询以返回医生的姓名和专业,患者的姓名和疾病以及预约日期?

到目前为止,我已经到了这里:

SELECT person.name, doctor.specialty, pacient.disease, appointment.date
FROM appointment
INNER JOIN person
ON appointment.pacient_id=person.id
INNER JOIN doctor
ON appointment.doctor_id=doctor.id_person
INNER JOIN pacient
ON appointment.pacient_id=pacient.id_person

但这并没有回归正确的领域。我认为问题在于为同一行中的两个不同的id(doctor和pacient)返回相同的字段(person.name)。

1 个答案:

答案 0 :(得分:1)

您需要对person表执行两个单独的连接,并使用别名来标识各个表,如下所示:

select 
    dp.name as DoctorName
  , doctor.specialty
  , pp.name as PacientName
  , pacient.disease
  , appointment.date
from appointment

  inner join doctor
   on appointment.doctor_id = doctor.id_person
  inner join person dp
   on appointment.doctor_id = dp.id

  inner join pacient
   on appointment.pacient_id = pacient.id_person
  inner join person pp
   on appointment.pacient_id = pp.id