简体   繁体   中英

SELECT or JOIN using two tables with similar columns

Brief Overviw and Relationship Info

One Mentor may mentor several Mentees in a 1:N relationship which is optional on both ends, therefore there may be managers who don't mentor any other managers and also managers who are not mentored by another manager. Both Mentors and Mentees are represented by their respective Number which is also their Manager Number from the Manager table.

Given Schema

The Employee table has the following columns:

  • Employee_Number
  • Name
  • Home Address
  • Telephone Number

The Manager table contains:

  • Manager_Number
  • Employee_Number (linked with foreign key to Employee table)

The Mentor table contains:

  • Mentee_Number (linked with foreign key to Manager table[Manager_Number])
  • Mentor_Number (also linked with foreign key to Manager table[Manager_Number])

What's required and what I tried

I am trying to do a JOIN so that I can see following columns:

  • Mentor's Manager Number
  • Mentor's Name
  • Mentee's Manager Number
  • Mentee's Name

I have the following join statement, which does not seem to work and I am unsure why:

SELECT
  man.manager_number,
  man.employee_number AS mentor_employee,
  emp.name AS mentor_name,
  man2.employee_number AS mentee_employee,
  emp2.name AS mentee_name
FROM 
  manager man
INNER JOIN
  employee emp
ON
  emp.employee_number = man.employee_number 
INNER JOIN
  mentor men
ON
  man.manager_number= men.mentor_number
INNER JOIN
  employee emp2
ON
 emp2.employee_number = man2.employee_number 
INNER JOIN
  mentor men
ON
  man.manager_number= men.mentee_number;

Any help would be greatly appreciated!

Keeping aside the logic you need, you have some issues to fix:

ON
 emp2.employee_number = man2.employee_number /* <---- no MAN2 alias */
INNER JOIN
  mentor men                                 /* <---- same alias MEN than before */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM