[英]Joining three tables with parent-child relationship
假設我們具有以下結構的四個表(表名稱-字段):
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
)。
您需要對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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.