如何优化多个表中的多个子查询?

时间:2016-02-12 15:10:11

标签: mysql sql

我有两个表,例如 tnx_lc_invoice tnx_lc_payment 。我想从这两个表中生成报告。

表格架构如下图所示

tnx_lc_payment

enter image description here

tnx_lc_invoice

enter image description here

我想生成如下图像

的输出

输出

enter image description here

我正在尝试下面的查询,它生成类似的输出。但我想优化此查询或任何替代解决方案以获得更快的结果。

SELECT
    a.lc_no,
    a.invoiceValue,
    b.paymentValue,
    (
        a.invoiceValue - b.paymentValue
    ) AS shortPaymentValue
FROM
    (
        SELECT
            lc_no,
            sum(invoice_value) AS invoiceValue
        FROM
            tnx_lc_invoice
        GROUP BY
            lc_no
    ) a
INNER JOIN (
    SELECT
        lc_no,
        sum(payment_value) AS paymentValue
    FROM
        tnx_lc_payment
    GROUP BY
        lc_no
) b ON a.lc_no = b.lc_no

如果有其他替代方案,请告诉我。谢谢。

1 个答案:

答案 0 :(得分:0)

不使用子查询而是在它们之间创建内部直接

    SELECT
        a.lc_no,
        sum(a.invoice_value) AS invoiceValue,
        sum(b.payment_value) AS payment_value,
        (sum(a.invoice_value) - sum(b.paymentValue)) AS shortPaymentValue
    FROM       tnx_lc_invoice a
    INNER JOIN tnx_lc_payment b      
    ON a.lc_no = b.lc_no
    GROUP BY
        a.lc_no

查询不正确,因为如果发票和付款在同一个lc_no上重复,它会将行相乘。

因此有必要在内部查询中添加至少一个组。

SELECT
        a.lc_no,
        sum(a.invoice_value) AS invoiceValue,
        sum(b.payment_value) AS payment_value,
        sum(a.invoice_value) - sum(b.payment_Value) AS shortPaymentValue
    FROM  (select lc_no, sum(invoice_value) as invoice_value 
           from tnx_lc_invoice group by lc_no) a
    INNER JOIN tnx_lc_payment b      
    ON a.lc_no = b.lc_no
    GROUP BY
        a.lc_no