PHP MySQL选择SUM减去SUM

时间:2017-02-17 01:02:38

标签: php mysql

我正在尝试运行如下的查询:

SELECT (SUM(amount) - SUM(refundAmount)) as amount FROM orders WHERE $invoiceFilter AND $websiteFilter

正确获取金额列的总和,但不会减去退款金额。

像这样的查询的正确语法是什么?

3 个答案:

答案 0 :(得分:1)

您可能遗漏了类似参考列的内容,以过滤您需要处理的数据。类似的东西:

SELECT (SUM(amount) - SUM(refundAmount)) AS amount 
FROM orders 
WHERE 
    <a_column> = $invoiceFilter 
    AND <another_column> = $websiteFilter;

答案 1 :(得分:1)

试试这个:

SELECT SUM(amount - refundAmount) AS `amount` 
FROM orders 
WHERE 
    invoice = $invoiceFilter 
    AND website = $websiteFilter;

答案 2 :(得分:1)

您可以在FROM子句中使用子查询。

SQL:

SELECT amount - refund
FROM (SELECT SUM(amount) as amount
      FROM orders
      WHERE invoice = 'invoiceFilter' AND website = 'websiteFilter') as a,
     (SELECT SUM(refundAmount) as refund
      FROM orders
      WHERE invoice = 'invoiceFilter' AND website = 'websiteFilter') as b;

PHP:

mysql_query("SELECT amount - refund
             FROM (SELECT SUM(amount) as amount
                   FROM orders
                   WHERE invoice = '" . mysql_real_escape_string($invoiceFilter). "'
                   AND website = '" . mysql_real_escape_string($websiteFilter). "') as a,
                  (SELECT SUM(refundAmount) as refund
                   FROM orders
                   WHERE invoice = '" . mysql_real_escape_string($invoiceFilter). "'
                   AND website = '" . mysql_real_escape_string($websiteFilter). "') as b; ");