简体   繁体   中英

MySQL - How to select Multiple rows from Multiple tables

I have a question about a SQL statement, for some reason my script is not working properly.. This is the Scenario; I have 6 tables

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

My Script: I need get all the rows from those 5 tables. I am not really good for SQL Indexes validation, that's why my script is not working properly !

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'

It would be simpler if you use explicit JOINS rather than comma-delimited tables:

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'
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'

Try this and see

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM