这是一个难以理解的问题,但这里是表格:
*的 STUDENT
ID pk
ASSIGNED_ADVISOR_ID fk ref(DEP_FACULTY.ID)
FNAME
L-NAME
*的 DEP_FACULTY
ID
FNAME
L-NAME
*的 ADVISE_HIST
student_id数据
ACTUAL_ADVISOR_ID fk ref(DEP_FACULTY.ID)
继承问题:
学生可以由他们的ASSIGNED_ADVISOR_ID
以外的教师(ACTUAL_ADVISOR_ID
)告知,我需要一个查询,加入这3个表,这些表将返回学生姓名,指定的顾问姓名,以及实际的顾问名称(以及我不会列出的其他内容)。
我的查询:
select
CONCAT(STUDENT.LNAME,', ',STUDENT.FNAME),
CONCAT(DEP_FACULTY.LNAME,', ',DEP_FACULTY.FNAME) as "ASSIGNED ADVISOR",
***need a field here for actual advisor***
from
STUDENT
join DEP_FACULTY on STUDENT.ASSIGNED_ADVISOR_ID=DEP_FACULTY.ID
left join ADVISE_HIST on STUDENT.ID=ADVISE_HIST.STUDENT_ID;
有没有办法再次显示DEP_FACULTY.LNAME
和FNAME
,但这次引用了ACTUAL顾问?
或者我是否需要向ADVISE_HIST
(ADVISE_HIST.DEP_FACULTY_LNAME
和ADVISE_HIST.DEP_FACULTY_FNAME
)添加冗余以正确返回此信息?
答案 0 :(得分:1)
select
CONCAT(STUDENT.LNAME,', ',STUDENT.FNAME),
CONCAT(DEP_FACULTY.LNAME,', ',DEP_FACULTY.FNAME) as `ASSIGNED ADVISOR`,
CONCAT(ACTUAL.LNAME, ', ', ACTUAL.FNAME) AS `ACTUAL ADVISOR`
from
STUDENT
join DEP_FACULTY on STUDENT.ASSIGNED_ADVISOR_ID=DEP_FACULTY.ID
left join ADVISE_HIST on STUDENT.ID=ADVISE_HIST.STUDENT_ID
/* JOIN again between DEP_FACULTY and ADVISE_HIST with an alias */
LEFT JOIN DEP_FACULTY AS ACTUAL ON ADVISE_HIST.ACTUAL_ADVISOR_ID = ACTUAL.ID