I have a query which looks something like this (the actual table and column names are MUCH longer, it's a mess, and there are actually SIX fields I need to retrieve from the FieldSummary table but I haven't written out the whole query yet!)
select
rh.RequirementDate,
rt.RequirementType,
f1s.Summary as F1,
f2s.Summary as F2,
f3s.Summary as F3
from
RequirementHistory rh
join RequirementTypeLU rt on rh.RequirementTypeLUID = rt.RequirementTypeLUID
left join FieldSummary fs1 on rh.RequirementHistoryID = fs1.RequirementHistoryID -- all these identical joins, there's gotta be a better way...
left join Field f1 on fs1.FieldID = f1.FieldID
left join FieldSummary fs2 on rh.RequirementHistoryID = fs2.RequirementHistoryID
left join Field f2 on fs2.FieldID = f2.FieldID
left join FieldSummary fs3 on rh.RequirementHistoryID = fs3.RequirementHistoryID
left join Field f3 on fs3.FieldID = f3.FieldID
where
rh.LinkedEntityID = 3
and f1.ScreenDescription = 'Field 1' -- this ScreenDescription lookup looks really brittle...
and f2.ScreenDescription = 'Field 2'
and f3.ScreenDescription = 'Field 3'
So I'm taking the RequirementHistory and RequirementTypeLU (lookup) tables, and joining them to the FieldSummary (actually data entered in the fields, not sure why it's called a summary) and Field (the field definitions) tables to retrieve the field data, once for each field (the actual field names are specified in the where clause as ScreenDescription). It's some sort of weird modular thing where system administrators can define their own "additional fields" to link to whatever entity types they want in the system. I know it looks horrible, I didn't design it!
Now my problem is I'm not getting any results. I'm sure something is wrong with my joins, but I'm not sure what. I also tried placing the ScreenDescription comparisons in the joins to Field, but that resulted in a ridiculous number of duplicate results, expanding with each pair of joins I added! What can I do to make this work properly? Ideally I want something like this as my results:
RequirementDate RequirementType F1 F2 F3
10/07/1983 Someone's birthday some data here
09/11/2001 A disaster more data here
01/20/2021 Recovery! At last! still more data
Where RequirementDate and RequirementType are pulled from their respective tables, and F1-3 are pulled from the FieldSummary table by looking up the appropriate field from Field using the ScreenDescription supplied in the where
clause.
I know this is a huge mess but I'm trying to do my best with the database structure I have!