mysql查询返回引用2个不同外键的相同字段

时间:2012-03-11 03:40:55

标签: mysql sql database foreign-keys

这是一个难以理解的问题,但这里是表格:

*的 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.LNAMEFNAME,但这次引用了ACTUAL顾问?

或者我是否需要向ADVISE_HISTADVISE_HIST.DEP_FACULTY_LNAMEADVISE_HIST.DEP_FACULTY_FNAME)添加冗余以正确返回此信息?

1 个答案:

答案 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