如何在 MySQL SUM 子查询中创建可用的别名
How to create usable alias in MySQL SUM subquery
在下面的 MySQL 查询中,我能够生成一个 Sum 值,但无法分配可用于在 PHP 页面中回显的值。
SELECT
invoices.InvoiceNo AS Invoice,
invoices.invDate AS DATE,
invoices.invValue AS Amount,
(
SELECT SUM(invoices.invValue) AS GrandTotal
FROM invoices
WHERE invoices.fKey = 186 AND inv_openClosed = 0
)
FROM invoices
WHERE invoices.fKey = 186 AND inv_openClosed = 0
ORDER BY Invoice DESC
测试显示结果,但 "GrandTotal" 的别名不起作用。并且MySQL没有错误去寻求解决方案。
查询结果如下:
与其在子查询中使用别名,不如为其结果设置别名:
SELECT
invoices.InvoiceNo AS Invoice,
invoices.invDate AS DATE,
invoices.invValue AS Amount,
(
SELECT SUM(invoices.invValue)
FROM invoices
WHERE invoices.fKey = 186 AND inv_openClosed = 0
) AS GrandTotal
FROM invoices
WHERE invoices.fKey = 186 AND inv_openClosed = 0
ORDER BY Invoice DESC
别名需要在外部查询中而不是内部查询:
SELECT i.InvoiceNo AS Invoice,
i.invDate AS DATE,
i.invValue AS Amount,
(SELECT SUM(i2.invValue)
FROM invoices i2
WHERE i2.fKey = 186 AND i2.inv_openClosed = 0
) AS GrandTotal
FROM invoices i
WHERE i.fKey = 186 AND i.inv_openClosed = 0
ORDER BY i.Invoice DESC;
您会注意到我还包含了 table 别名和限定的列名。你也可以把它写成一个相关的子查询,所以你不需要重复常量:
(SELECT SUM(i2.invValue)
FROM invoices i2
WHERE i2.fKey = i.fKey AND i2.inv_openClosed = i.inv_openClosed
) AS GrandTotal
而在 MySQL 8+ 中,您可以使用 window 函数:
SELECT i.InvoiceNo AS Invoice,
i.invDate AS DATE,
i.invValue AS Amount,
SUM(i.invValue) OVER (PARTITION BY fKey, inv_openClosed) as GrandTotal
FROM invoices i
WHERE i.fKey = 186 AND i.inv_openClosed = 0
ORDER BY i.Invoice DESC;
在下面的 MySQL 查询中,我能够生成一个 Sum 值,但无法分配可用于在 PHP 页面中回显的值。
SELECT
invoices.InvoiceNo AS Invoice,
invoices.invDate AS DATE,
invoices.invValue AS Amount,
(
SELECT SUM(invoices.invValue) AS GrandTotal
FROM invoices
WHERE invoices.fKey = 186 AND inv_openClosed = 0
)
FROM invoices
WHERE invoices.fKey = 186 AND inv_openClosed = 0
ORDER BY Invoice DESC
测试显示结果,但 "GrandTotal" 的别名不起作用。并且MySQL没有错误去寻求解决方案。
查询结果如下:
与其在子查询中使用别名,不如为其结果设置别名:
SELECT
invoices.InvoiceNo AS Invoice,
invoices.invDate AS DATE,
invoices.invValue AS Amount,
(
SELECT SUM(invoices.invValue)
FROM invoices
WHERE invoices.fKey = 186 AND inv_openClosed = 0
) AS GrandTotal
FROM invoices
WHERE invoices.fKey = 186 AND inv_openClosed = 0
ORDER BY Invoice DESC
别名需要在外部查询中而不是内部查询:
SELECT i.InvoiceNo AS Invoice,
i.invDate AS DATE,
i.invValue AS Amount,
(SELECT SUM(i2.invValue)
FROM invoices i2
WHERE i2.fKey = 186 AND i2.inv_openClosed = 0
) AS GrandTotal
FROM invoices i
WHERE i.fKey = 186 AND i.inv_openClosed = 0
ORDER BY i.Invoice DESC;
您会注意到我还包含了 table 别名和限定的列名。你也可以把它写成一个相关的子查询,所以你不需要重复常量:
(SELECT SUM(i2.invValue)
FROM invoices i2
WHERE i2.fKey = i.fKey AND i2.inv_openClosed = i.inv_openClosed
) AS GrandTotal
而在 MySQL 8+ 中,您可以使用 window 函数:
SELECT i.InvoiceNo AS Invoice,
i.invDate AS DATE,
i.invValue AS Amount,
SUM(i.invValue) OVER (PARTITION BY fKey, inv_openClosed) as GrandTotal
FROM invoices i
WHERE i.fKey = 186 AND i.inv_openClosed = 0
ORDER BY i.Invoice DESC;