Convert a SQL subquery into a join when looking at another record in the same table Access 2010

十年热恋 提交于 2019-12-01 11:51:34

The very first thing is that you have a relational situation but the table structure you have is using columns to represent relationships. This gives you the R01, R02, R03 ... R13 columns on your table. Unfortunately you will not be able to change performance dramatically because your table structure is repetitive denormalized instead of relational. This means that your query will need all this repetitive code, as you mentioned repeating 13 times. That also means that your switch function can be replaced by a join but again will be repeated 13 times.

Right, now back to your query, you have multiple sub-selects on your query and you need to join the related tables on a left join on the FROM clause and use the new related alias on your select. now you will see on the example below that for each R01, R02 field you will have a Fam2, Fam3 relation and you will need to do this 13 times on your case, and for each one you need to link to the relatives table (as i did called Relat2, Relat3, etc). Now if you can change your database structure for a normalized structure, you could really simplify this query and use much simpler joins.

See if this one helps you understand the process:

SELECT People.ID, People.aacode, People.PERSNO,  
       People.HRP, People.DVHsize, xMarSta.Marital, 
       [Marital] & " (" & [People.AgeCat] & ")" & [RAL2] & [RAge2] &  
       [RAL3] & [RAge3] AS HsTyp, 
       Fam2.R01 AS Rel2,
       Fam3.R01 AS Rel3, 
       Relat2.Relationship as RAL2,
       Relat3.Relationship as RAL3,
       Fam2.AgeCat AS RAge2, 
       Fam3.AgeCat AS RAge3 
FROM (((((People
LEFT JOIN (People  AS Fam2) ON (Fam2.aacode = People.aacode  and Fam2.PERSNO = 2))
LEFT JOIN (Relatives as Relat2) on Relat2.Id = Fam2.R01)
LEFT JOIN (People as Fam3)   ON (Fam3.aacode = People.aacode  AND Fam3.PERSNO = 3))
LEFT JOIN (Relatives as Relat3) on Relat3.Id = Fam3.R01)
LEFT JOIN xMarSta ON xMarSta.ID=People.xMarSta)
WHERE (People.HRP=[People.PERSNO])
ORDER BY People.aacode; 

Joining a table to it self is done with an alias

e.g.

Select * From [Table1] Join [Table1] t1 on T1.SomeField = Table1.SomeOtherField

etc..

Probaly won't have time to fix it, but the real problem is where you've denormalised with R01, R02 etc.

You should have an other table RelationshipID PersonFrom PersonTo

You need to manage that though when creating relations and it will mean changes to your UI and logic.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!