从一个表中收集所有记录,并从另一个表中收集一个字段

时间:2017-03-30 21:24:41

标签: mysql

我尝试获取客户端的所有invoices,然后从payments计算SUM。问题是,来自paid_to_date的SUM在所有返回的行上都是相同的值。

Here's a SQLFiddle

SELECT `invoices`.*, 
       DATE_FORMAT(`invoices`.`due_date`, '%M %d, %Y') AS `due_date`,
       totals.`paid_to_date`
FROM   `invoices`, 
       (SELECT `payments`.`invoice_id`, 
               SUM(`payments`.`amount`) `paid_to_date`
        FROM   `payments` 
        GROUP  BY `payments`.`invoice_id`) AS totals 
WHERE  `invoices`.`client_id` = 1
ORDER  BY `invoices`.`due_date` DESC

1 个答案:

答案 0 :(得分:1)

您需要执行JOIN而不是在FROM语句中调用这两个表。

SELECT `invoices`.*, 
       DATE_FORMAT(`invoices`.`due_date`, '%M %d, %Y') AS `due_date`, 
       totals.`paid_to_date` 
FROM   `invoices`
LEFT JOIN    (SELECT `payments`.`invoice_id`, 
                  SUM(`payments`.`amount`) `paid_to_date` 
              FROM   `payments` 
              GROUP  BY `payments`.`invoice_id`) AS totals 
                  ON `invoices`.`ID` = `totals`.`invoice_id`
WHERE  `invoices`.`client_id` = 1 
ORDER  BY `invoices`.`due_date` DESC 

修改:已更改为LEFT JOIN,因为我不知道您希望看到未付的发票

包括SQL Fiddle以按预期证明查询功能。 http://sqlfiddle.com/#!9/50f08e/2

如评论中所述,您可能有错误的主键和外键。在您的SQL小提琴中,我更改了您的付款发票ID,因为它们将转到不存在的发票。