0

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Luke T O'Brien
  • 2,565
  • 3
  • 26
  • 38
  • When it comes to "= (SELECT", I'm always a bit concerned - can more than 1 row be returned?!? Use IN, or aggregate or limit etc to make sure always 1 row (or less.) – jarlh Apr 21 '15 at 09:44
  • Thanks for the edit @jarlh, yes I guess as it is more than 1 row can be returned, this is still a work in process. Could this be done better with multiple joins in the main statement? I think subquerys are inefficient. But how to do this in Entity Framework is beyond me – Luke T O'Brien Apr 21 '15 at 10:21

0 Answers0