复杂的SQL查询。至少对于我来说

时间:2012-07-13 18:44:39

标签: mysql sql

我正在尝试根据PatientID从我的数据库中提取发票数据。我想弄清楚哪些发票属于哪个病人。这是我结构的重要部分。

发票表

InvoiceNumber | DateInvoice | DueDate | StudyID | TypeInvoice 

患者表

FirstName | LastName | PatientID

InvoiceFields

id | InvoiceNumber | PatientID | 

我需要根据PatientID列出发票表数据。下面是我尝试的查询,但没有在哪里。谢谢你的时间。

SELECT    Distinct
          invoicefields.InvoiceNumber,
          invoices.DateInvoice
FROM      `invoices`, `patients`, `invoicefields`
WHERE     invoicefields.PatientID = patients.PatientID
          and invoicefields.InvoiceNumber = invoicefields.InvoiceNumber
GROUP BY  invoicefields.InvoiceNumber

2 个答案:

答案 0 :(得分:2)

SELECT InvT.InvoiceNumber, InvT.DateInvoice
FROM InvoiceTable InvT
INNER JOIN InvoiceFields InvF ON InvF.InvoiceNumber = InvT.InvoiceNumber AND InvF.PatientID = @PatientID

因此,您只需要InvoiceTable中的数据,并且表明您拥有PatientID。我建议您加入Cross Reference表InvoiceFields并使用该查询中的PatientID列将其过滤到您需要的内容。在我意识到你不需要患者的任何东西之前,我有一个使用存在的更复杂的例子。

如果您还需要有关患者的信息,您可以使用此功能(只需将所需的列放入选择中)

SELECT InvT.InvoiceNumber, InvT.DateInvoice
FROM InvoiceTable InvT
INNER JOIN InvoiceFields InvF ON InvF.InvoiceNumber = InvT.InvoiceNumber AND InvF.PatientID = @PatientID
INNER JOIN Patient Pat ON Pat.PatientID = InvF.PatientID

您可以将@PatientID部分放在Patient或InvoiceFields的连接上。如果索引是正确的,那么两种方式之间确实不应该存在性能差异。

对以下评论的回应,但我可以向其展示清洁:

SELECT  IT.InvoiceNumber
       ,IT.DateInvoice
FROM    InvoiceTable InvT
WHERE   EXISTS (SELECT  InvF.PatientID
                FROM    InvoiceFields InvF
                WHERE   InvF.InvoiceNumber = InvT.InvoiceNumber
                AND InvF.PatientID = @PatientID)

这将从InvoiceTable返回患者的所有行,如果InvoiceNumber为Unique,则不会有任何重复。通过这种方式,您只能访问InvoiceTable以从中返回数据。如果你只想要一个TOP 1:

SELECT  TOP 1 IT.InvoiceNumber
       ,IT.DateInvoice
FROM    InvoiceTable InvT
WHERE   EXISTS (SELECT  InvF.PatientID
                FROM    InvoiceFields InvF
                WHERE   InvF.InvoiceNumber = InvT.InvoiceNumber
                AND InvF.PatientID = @PatientID)

答案 1 :(得分:1)

SELECT * from invoices i
inner join invoicefields iFld
    on i.invoiceNumber = iFld.invoiceNumber
inner join patients p
    on iFld.patientID = p.patientID
    and p.patientID = 1235125

这应该让你至少开始朝着正确的方向前进。我不确定你想要返回哪些列和/或表中是否有任何空值。 Null将影响返回哪些行