2013-05-21 45 views
1

我有一個關於SQL語句的問題,由於某種原因,我的腳本無法正常工作.. 這是場景;我有6個表MySQL - 如何從多個表中選擇多行

Patient 
-PatientID 
-PatientName 
-EmployerID FK to employer.EmployerID. 

Employer 
-EmployerID 
-EmployerName 

Carrier 
-CarrierID 
-CarrierName 

Appointment 
-AppointmentID 
-AptDateTime 
-PatientID FK to patient.PatientID 

InsurancePlan 
-PlanID 
-GroupName 
-EmployerID FK to employer.EmployerID 
-CarrierID FK to carrier.CarrierID 

Inssub 
-InsubID 
-DateEffective 
-PlanID FK to insplan.PlanID 
-Suscriber FK to patient.PatientID 

我的腳本:我需要從這5個表中獲取所有行。我對SQL索引驗證不太好,這就是爲什麼我的腳本無法正常工作!

SELECT p.PatientName, e.EmployerName, c.CarrierName, ip.GroupName, a.AptDateTime, i.DateEffective 

FROM patient p, employer e, inssub i, InsurancePlan ip, carrier c, appointment a 

WHERE e.EmployerNum = p.EmployerNum AND 
     i.Subscriber = p.PatientID AND 
     i.PlanID = ip.PlanID AND 
     ip.CarrierID = c.CarrierID AND 
     ip.employerID = e.EmployerID AND 
     ip.PlanID = i.PlanID AND 
      a.PatientID = p.PatientID AND 
      a.DateTStamp > '2013/01/01' AND  
     a.AptDateTime != '0001-01-01 00:00:00' 

回答

3

,如果你使用顯式這將是更簡單的聯接,而不是逗號分隔表:

SELECT p.PatientName, e.EmployerName, c.CarrierName, ip.GroupName, a.AptDateTime, i.DateEffective 
FROM patient p 
JOIN employer e ON p.EmployerID = e.EmployerID 
JOIN insuranceplan ip ON e.EmployerID = ip.EmployerID 
JOIN carrier c ON ip.CarrierID = c.CarrierID 
JOIN appointment a ON p.PatientID = a.PatientID 
JOIN inssub i ON p.PatientID = i.Subscriber AND ip.PlanID = i.PlanID 
WHERE a.DateTStamp > '2013/01/01' 
    AND a.AptDateTime != '0001-01-01 00:00:00' 
+0

@Jay,更新:額外列。如果這不能滿足您的需求,您是否可以發佈一些樣本數據,以及您期望看到的結果? – PinnyM

0
SELECT p.PatientName, e.EmployerName, c.CarrierName, ip.GroupName, a.AptDateTime 
FROM Patient p JOIN Employer e ON p.EmployerId=e.EmployerId 
JOIN Appointment a ON p.PatientId= a.PatientId 
JOIN InsurancePlan ip ON ip.EmployerId=e.EmployerId 
JOIN Carrier c ON c.CarrierId=ip.CarrierId 
Join Inssub i ON i.PlanId=ip.PlanId 
WHERE a.DateTStamp > '2013/01/01' 
AND a.AptDateTime != '0001-01-01 00:00:00' 

試試這個,看看

+0

缺少僱主加入。而'inssub'對於使用的SELECT並不是真的需要。你添加了我錯過的東西嗎? – PinnyM

+0

我在第一個陳述中包含了僱主自己。 –

+0

錯過了 - 我的歉意。但是這裏不需要'inssub'表。 – PinnyM