这是我的数据库架构:
我只想选择患者的所有约会并获得以下结果集:
我已尝试过以下加入:
SELECT [User].user_id,name, surname, [Appointment].day,[Appointment].month,[Appointment].year,[Appointment].hour,[Appointment].minutes
FROM [User]
LEFT JOIN [Doctor] ON [Doctor].user_id = [User].user_id
LEFT JOIN [Patient] ON [Patient].user_id = [User].user_id
LEFT JOIN [Appointment] ON [Doctor].doctor_id = [Appointment].doctor_id and [Patient].patient_id = [Appointment].patient_id
但我没有得到所需的输出!
答案 0 :(得分:2)
您需要多次引用User表,以便在同一结果记录中为医生和患者提供单独的详细信息。您拥有的只能在医生和患者相同的用户时显示结果。
这进一步意味着您需要使用表别名,这样您就可以区分要引用的User表的哪个实例。看起来INNER JOIN比LEFT JOIN更合适。
由于问题陈述表明患者是您的起点,我会将其作为您的第一个/ FROM表并从那里开始:
SELECT a.appointment_id "Appointment ID", ud.name + ' ' + ud.surname "Doctor Name",
up.name + ' ' + up.surname "Patient Name",
a.Day, a.Month, a.Year, a.Hour, a.Minute
FROM Patient p
INNER JOIN User up ON up.user_id = p.user_id
INNER JOIN Appointments a ON a.patient_id = p.patient_id
INNER JOIN Doctor d on d.doctor_id = a.doctor_id
INNER JOIN User ud ON ud.user_id = d.user_id
最后,似乎单个DateTime
列比单独的Year,Month,Day等列更适合Appointments表。