I have been working on how to map an entity property to a column in another table using multiple joins (or a subquery), but I am really struggling to find where to start.
I have create a SQL Fiddle that demonstrates what I want to do. A User
entity should contain a property called Employee
that selects the name from the employee table
SET @uid = 2;
SELECT Employee.Name
FROM Employee
JOIN Company ON Employee.CompanyId = Company.Id
WHERE Company.CompanyNo = (SELECT UserEmployee.CompanyNo
FROM UserEmployee
JOIN User ON UserEmployee.UserId = User.Id
AND User.Id = @uid)
AND Employee.EmployeeNo = (SELECT UserEmployee.EmployeeNo
FROM UserEmployee
JOIN User ON UserEmployee.UserId = User.Id
AND User.Id = @uid)
http://sqlfiddle.com/#!9/cbac3/2
Basically, a User
record is linked with a Employee
using a relationship table (UserEmployee
), however this is a 1-0 relationship.
We are not using Ids as foreign keys, instead each Employee
has a EmployeeNo
and has a 1-1 relationship with a Company
that has it's own CompanyNo
, so the composite foreign key for the UserEmployee
table is made up of the Employee and Company Numbers.
I cannot link to the EmployeeId directly in the UserEmployee
table as in the actual system employee records are duplicated (for history keeping reasons) and there is a third table added into the mix.
Thank you