从多个表返回数据

时间:2019-09-14 12:17:17

标签: mysql sql inner-join

谁能帮我解决此SQL查询。

Select c.name, c.address, c.area, sum(i.amount) from customers c 
Inner Join invoices i on c.id=i.customer_id 
Inner Join invoice_payments p on i.id = p.invoice_id 
group by c.name

这是表格结构

客户表

id(int), Name(string), Area(string), Address(string)

发票表

id(int), Invoice_Number (string), customer_id(int), amount(decimal)

enter image description here

发票付款

id(int), invoice_id(int), amount(decimal)

enter image description here

我在invoice_payments表中有一个客户的两条付款记录,因此它返回的是该客户的两倍...

我如何解决此问题

提供的查询返回以下结果。 enter image description here

3 个答案:

答案 0 :(得分:2)

分别计算这两个总和并加入它们:

select 
  ci.name, ci.address, ci.area, 
  ci.invoice_amount, cp.invoice_payments_amount 
from (
  select c.id, c.name, c.address, c.area, sum(i.amount) invoice_amount
  from customers c inner join invoices i on c.id = i.customer_id 
  group by c.id, c.name, c.address, c.area
) ci  inner join (
  select c.id, sum(p.amount) invoice_payments_amount 
  from customers c 
  inner join invoices i on c.id = i.customer_id 
  inner join invoice_payments p on i.id = p.invoice_id
  group by c.id
) cp on cp.id = ci.id

答案 1 :(得分:1)

您根本没有使用invoice_payments表,因此从查询中将其删除。另外,修复group by以在select中包括 all 个未聚合的列:

select c.name, c.address, c.area, sum(i.amount)
from customers c join
     invoices i
     on c.id = i.customer_id 
group by c.name, c.address, c.area;

答案 2 :(得分:1)

这应该为您工作

Select c.name, c.address, c.area
, sum(i.amount) amount
,SUM(i.amount - p.amount) unpaid_amount 
from customers c 
Inner Join invoices i on c.id=i.customer_id 
Inner Join  (SELECT SUM(amount) amount,invoice_id 
             FROM invoice_payments 
             GROUP BY invoice_id) p on i.id = p.invoice_id 
group by c.name ;

其结果是(我将自己的数据a放入custormer表中)

name            address            area     amount  unpaid_amount
Donald Duck     helsinki stret 56  51       9000    0
Donald Trump    Trump Towers 1     52       2325    0