MySQL内连接和两列求和

2022-01-09 00:00:00 sum mysql inner-join

我有以下表格

表格:约会

ID | PRICE | PAID
48 |  100  | 180

表格:约会产品

ID | APPOINTMENT_ID | PRODUCT_ID | TOTAL
10 |       48       |      1     | 30
11 |       48       |      9     | 30
12 |       48       |      6     | 30

我想以某种方式运行一个 MySQL 查询:

I Would like to somehow run a MySQL query that will:

a) 加入这两个表,对每个约会 ID 的约会产品的总计"求和,如果付费"不等于价格(来自约会表)+总计(来自约会产品表),则显示它.

a) join the two tables, SUM the "TOTAL" of appointments_products for each appointment_id and if the "PAID" is not equal of the PRICE (from appointments table) + TOTAL (from appointments_products table) then to show it.

这是我到目前为止所做的:

This is what I have done so far:

select a.*, b.appointment_id as AppId, b.total as ProdTotal 
from appointments a 
INNER JOIN appointments_products b ON a.id = b.appointment_id

但是这个查询不会对每个约会ID的总数求和

But this query does not sum the total for each appointment_id

推荐答案

select a.ID,a.PRICE,a.PAID,a.id as AppId,
       sum(b.total) as ProdTotal 
from appointments a 
INNER JOIN appointments_products b ON a.id = b.appointment_id
group by a.ID,a.PRICE,a.PAID;

相关文章