1

这将很难解释。

tbl_customers每天都会循环浏览我的客户记录数次。

SELECT c.* FROM tbl_customers c

我只是退回客户的:customerid,,,,namephoneemail

现在奇怪的部分。我想在电子邮件之后再附加 3 列:totalpaid、totalowed、totalbalance 但是,这些列名在任何地方都不存在。

以下是我如何查询每个:(作为单个查询)

SELECT SUM(total) AS totalpaid 
FROM tbl_customers_bills 
WHERE customerid = X
AND billtype = 1

SELECT SUM(total) AS totalowed 
FROM tbl_customers_bills 
WHERE customerid = X
AND billtype = 2

SELECT SUM(total) AS totalbalance 
FROM tbl_customers_bills 
WHERE customerid = X
AND billtype IN(1,2)

因此,这billtype是告诉我记录是否已支付的列。

我在这里不知所措。如何将 3 个单独的查询和到第一个查询的循环中?

4

2 回答 2

5

只需将客户加入账单并计算总和即可。要分离出totalpaid 和totalowed,您可以使用SUM(CASESUM(IFwless1's answer所示

SELECT c.*,
        SUM(CASE WHEN billtype = 1 THEN total ELSE 0 END) totalpaid ,
        SUM(CASE WHEN billtype = 2 THEN total ELSE 0 END) totalowed ,
        SUM(total) AS totalbalance
FROM 
    tbl_customers c
    LEFT JOIN tbl_customers_bills  b
    ON c.customerid = b.customerid
     and billtype in (1,2)
GROUP BY 
     c.customerid

因为这是 MySQL 你只需要对客户的 PK 进行分组。

于 2013-01-09T23:34:29.917 回答
3

您可以使用 、 和 的组合来执行GROUPSUM操作IF

SELECT c.id, c.name, c.phone, c.email, 
SUM(IF(b.billtype = 1, b.total, 0)) AS totalpaid,
SUM(IF(b.billtype = 2, b.total, 0)) AS totalowed,
SUM(IF(b.billtype = 1 OR b.billtype = 2, b.total, 0)) AS totalbalance,
FROM tbl_customers c LEFT JOIN tbl_customers_bills b ON b.customerid = c.id
GROUP BY c.id

请参阅: http: //dev.mysql.com/doc/refman/5.0/en//group-by-functions.html http://dev.mysql.com/doc/refman/5.0/en/control-flow-函数.html

于 2013-01-09T23:35:25.497 回答