连接和嵌套查询 - 多表 (4+)

Joins and Nested Queries - multiple tables (4+)

RDMBS:甲骨文 嵌套查询是一项要求。

我正在尝试收集所有在 2014 年 3 月有预约的患者,并显示他们看了什么医生,以及他们被诊断出患有什么疾病。然后显示预约 ID、患者全名、年龄、性别和 phone,并显示医生全名和 phone。我能够做到大部分,直到我问病人被诊断出什么。

此代码允许我访问 2014 年 3 月的患者和医生记录:

Select Appointment.appointmentid, patient.surname ||','|| patient.given as     Patient, trunc(((sysdate-patient.dob)/365),0) as Patient_Age, patient.phonehome as Patient_Contact, doctor.Surname ||','|| doctor.given as Doctor, doctor.phone as Doctor_Contact
from doctor, patient, appointment 
where doctor.doctorid=appointment.doctorid
and patient.patientid=appointment.patientid
and extract(month from dateofappointment) = '03'
and extract(year from dateofappointment) = '2014';

但是当我放入嵌套查询进行诊断时,我得到了错误。

代码:

Select Appointment.appointmentid, patient.surname ||','|| patient.given as Patient, trunc(((sysdate-patient.dob)/365),0) as Patient_Age, patient.phonehome as Patient_Contact, disease.name as Diagnosis, doctor.Surname ||','|| doctor.given as Doctor, doctor.phone as Doctor_Contact
from doctor, patient, appointment 
where disease.name in (select disease.name
from disease
where disease.diseaseid=diagnosed.diseaseid
and diagnosed.appointmentid=appointment.appointmentid)
and doctor.doctorid=appointment.doctorid
and patient.patientid=appointment.patientid
and extract(month from dateofappointment) = '03'
and extract(year from dateofappointment) = '2014';

如有任何更正或建议,我们将不胜感激。

您没有引用 disease table。您可以像这样重写查询:

Select 
  Appointment.appointmentid, 
  patient.surname ||','|| patient.given as Patient, 
  trunc(((sysdate-patient.dob)/365),0) as Patient_Age, 
  patient.phonehome as Patient_Contact, 
  disease.name as Diagnosis, 
  doctor.Surname ||','|| doctor.given as Doctor, 
  doctor.phone as Doctor_Contact
from doctor
inner join appointment on doctor.doctorid         = appointment.doctorid
inner join patient     on patient.patientid       = appointment.patientid
inner join diagonsed   on diagnosed.appointmentid = appointment.appointmentid
inner join disease     on disease.diseaseid       = diagnosed.diseaseid
where extract(month from dateofappointment) = '03'
  and extract(year from dateofappointment) = '2014';

或者,使用相同的嵌套查询,您可以这样重写它:

Select 
  Appointment.appointmentid, 
  patient.surname ||','|| patient.given as Patient, 
  trunc(((sysdate-patient.dob)/365),0) as Patient_Age, 
  patient.phonehome as Patient_Contact, 
  disease.name as Diagnosis, 
  doctor.Surname ||','|| doctor.given as Doctor, 
  doctor.phone as Doctor_Contact
from doctor, appointment, patient, diagnosed, disease
where doctor.doctorid = appointment.doctorid
and appointment.patientid = patient.patientid
and diagnosed.appointmentid=appointment.appointmentid
and disease.diseaseid=diagnosed.diseaseid
and disease.name in (select disease.name
                       from disease
                       where disease.diseaseid=diagnosed.diseaseid)
and extract(month from dateofappointment) = '03'
and extract(year from dateofappointment) = '2014';