MySQL Inner join and sum two columns

梦想与她 提交于 2019-12-04 07:00:01

问题


I have the following tables

TABLE: appointments

ID | PRICE | PAID
48 |  100  | 180

TABLE: appointments_products

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

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

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

But this query does not sum the total for each appointment_id


回答1:


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;



回答2:


Use where to check if price is equal to paid and the use group by to group with appointment_id.




回答3:


select b.Appointment_Id, a.price, a.PAID, a.id, sum(b.total) AS TotalProd FROM appointments_products AS b inner join appointments as a On Appointment_Id = a.Id group by Appointment_Id, a.Price , a.PAID , a.id HAVING a.PAID != (a.Price + sum(b.Total))



来源:https://stackoverflow.com/questions/50676463/mysql-inner-join-and-sum-two-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!