MySQL内连接和两列求和 [英] MySQL Inner join and sum two columns

查看:27
本文介绍了MySQL内连接和两列求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下表格

表格:约会

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;

这篇关于MySQL内连接和两列求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆