我有两个表 appointments 和 line_items。
appointments
id integer primary key
price decimal
line_items
id integer primary key
price decimal
appointment_id integer foreign key
我需要获取 appointments.price 的总和以及相关联的 line_items 价格总和。
比如我有2个约会
id price
1 10
2 15
和订单项
id price appointment_id
1 10 1
2 15 1
3 10 2
3 20 2
总结果应该是 (10 + (10 + 15)) + (15 + (10 + 20))
目前我正在尝试这个查询。但它不起作用。
SELECT SUM(appointments.price + sum(line_items.price)) AS total_sum
FROM `appointments`
INNER JOIN 'line_items' ON 'line_items'.'appointment_id' = 'appointments'.'id'
最好的方法是什么?子查询 line_items.price 总和或连接总和 line_items.price。或者有其他更好的解决方案?
提前致谢!
最佳答案
我认为您正在寻找的是派生表中的 SUM() GROUP BY
,然后是带有 appointments
的 join
。像这样。
SELECT SUM(appointments.price + line_items.price) AS total_sum
FROM appointments
INNER JOIN
(
SELECT line_items.appointment_id,SUM(price) as price
line_items
GROUP BY appointment_id
) line_items ON line_items.appointment_id = appointments.id
关于mysql - 总和列与连接表的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30321926/