我尝试获取客户端的所有invoices
,然后从payments
计算SUM。问题是,来自paid_to_date
的SUM在所有返回的行上都是相同的值。
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
答案 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,因为它们将转到不存在的发票。