如何从多个表中获取具有混乱关系的记录

时间:2013-06-18 06:25:13

标签: mysql sql relation

enter image description here

您好!我一直在努力从这个架构中获取记录,真的不适合我..关系太乱了

PatPlan表的Ordinal字段是INT(1,2)
1 =主要保险
2 =二级保险

和关系字段(有主要保险的患者和有预约的患者之间的关系)以相同的方式工作     1 =自己     2 =配偶
    3 =孩子

并且inssub表订户是患者

我需要基本上获得三大类:

1. Appointment's Fields
   -AptDateTime
   -DateTStamp
   -Patient's FirstName
   -Patient's LastName
   -Patient's Gender
   -Patient's Position
   -Patient's EmployerName


2. Guarantor's fields 
   //Same as the Patient's fields (Guarantor is a patient)
   //Must be the guarantor related to the patient who has the appointment
   -Patient's FirstName
   -Patient's LastName
   -Patient's Gender
   -Patient's Position
   -Patient's EmployerName
   -CarrierName
   -EmployerName

3. Primary Insurance (This is the one i can't work it out)
   //Primary insurance is as same as the patient's table
   -Patient's FirstName
   -Patient's LastName
   -Patient's Gender
   -Patient's Position
   -Patient's EmployerName
   -CarrierName
   -EmployerName

我将非常感谢您的帮助,因为我已经在这3天工作了,但我还没有解决。

我目前的查询:

SELECT p.Title, p.FName, p.LName, p.Position, p.Gender,e.EmpName, 

pm.FName AS PMFname, pm.LName AS PMLName, pp.Relationship AS PMPatStatus, 
pme.EmpName AS PMEmpName, i.DateEffective AS PMDateEffective, i.DateTerm AS PMDateTerm, 
c.CarrierName AS PMCarrierName, pme.EmpName AS PMEmpName,

g.FName AS GFName, g.LName AS GLName, pp.Relationship AS GPatStatus, g.Gender AS GGender,ge.EmpName AS GEmpName,

a.AptDateTime, a.AptNum, a.PatNum

FROM patient p LEFT OUTER JOIN Employer e ON p.employerNum = e.employerNum
inner JOIN Appointment a ON a.PatNum = p.PatNum
left JOIN Insplan ip ON ip.EmployerNum = e.employerNum
left JOIN Carrier c ON c.carrierNum = ip.carrierNum 
left JOIN Inssub i ON i.PlanNum = ip.PlanNum 
left JOIN patplan pp ON  pp.InsSubNum = i.InsSubNum AND  pp.PatNum = p.PatNum 
left JOIN Patient pm ON pm.PatNum = i.subscriber 
left JOIN Employer pme ON pme.employerNum = pm.employerNum
left JOIN Patient g ON g.PatNum = p.Guarantor 
LEFT JOIN Employer ge ON ge.employerNum = g.employerNum

WHERE a.DateTStamp > '2012/06/03' AND 
a.AptDateTime != '0001-01-01 00:00:00'

0 个答案:

没有答案