lj_growl
lj_growl

Reputation: 123

Inner Join and Left Join on 5 tables in Access using SQL

I am attempting to access data from the following tables:

  1. OrgPlanYear
  2. ProjOrgPlnYrJunction
  3. DC
  4. DCMaxEEContribLevel
  5. DCNonDiscretionaryContribLevel

Basically, I need to inner join OrgPlanYear + DC and ProjOrgPlnYrJunction then I need to Left Join the remaining tables (tables 4 and 5) due to the fact the tables 1-3 have all the rows I need and only some have data in tables 4-5. I need several variables from each table. I also need the WHERE function to be across all fields (meaning I want all this data for a select group where projectID=919).

Please help!

I have tried many things with errors including attempting to use the Design Query side (i.e. JOIN function issues, badly formatted FROM function, etc.)! Here is an example of one excluding all variables I need:

SELECT 
ProjOrgPlnYrJunction.fkeyProjectID, OrgPlanYear.OrgName, DC.PlanCode, DCNonDiscretionaryContribLevel.Age,DCNonDiscretionaryContribLevel.Service

FROM 
(((OrgPlanYear INNER JOIN DC ON OrgPlanYear.OrgPlanYearID = DC.fkeyOrgPlanYearID) INNER JOIN ProjOrgPlnYrJunction ON OrgPlanYear.OrgPlanYearID = ProjOrgPlnYrJunction.fkeyOrgPlanYearID) 

LEFT JOIN
(SELECT DCNonDiscretionaryContribLevel.Age AS Age, DCNonDiscretionaryContribLevel.Service AS Service FROM DCNonDiscretionaryContribLevel WHERE ProjOrgPlnYrJunction.fkeyProjectID)=919) 

LEFT JOIN (
SELECT DCMaxEEContribLevel.EEContribRoth FROM EEContribRoth WHERE ProjOrgPlnYrJunction.fkeyProjectID)=919)

ORDER BY OrgPlanYear.OrgName;

Upvotes: 2

Views: 136

Answers (1)

Parfait
Parfait

Reputation: 107632

Main issues with your query:

  • Missing ON clauses for each LEFT JOIN.
  • Referencing other table columns in SELECT and WHERE of a different subquery (e.g., FROM DCNonDiscretionaryContribLevel WHERE ProjOrgPlnYrJunction.fkeyProjectID).
  • Unmatched parentheses around subqueries and joins per Access SQL requirements.

See below adjusted SQL that now uses short table aliases. Be sure to adjust SELECT and ON clauses with appropriate columns.

SELECT p.fkeyProjectID, o.OrgName, DC.PlanCode, dcn.Age, dcn.Service, e.EEContribRoth

FROM (((OrgPlanYear o
INNER JOIN DC 
   ON o.OrgPlanYearID = DC.fkeyOrgPlanYearID) 
INNER JOIN ProjOrgPlnYrJunction p
   ON o.OrgPlanYearID = p.fkeyOrgPlanYearID) 

LEFT JOIN
  (SELECT Age AS Age, Service AS Service 
   FROM DCNonDiscretionaryContribLevel
   WHERE fkeyProjectID = 919) AS dcn
     ON dcn.fkeyProjectID = p.fkeyOrgPlanYearID)

LEFT JOIN 
  (SELECT EEContribRoth 
   FROM EEContribRoth 
   WHERE fkeyProjectID = 919) AS e
     ON e.fkeyProjectID = p.fkeyProjectID

ORDER BY o.OrgName;

Upvotes: 2

Related Questions