sum列与连接表的总和

时间:2015-05-19 09:38:24

标签: mysql sql

我有两个表约会和line_items。

id price 
1 10 
2 15

我需要得到约会的总和。价格与line_items价格的相关总和之和。

例如,我有2个约会

id price appointment_id
1  10    1
2  15    1
3  10    2
3  20    2

和订单项

SELECT SUM(appointments.price + sum(line_items.price)) AS total_sum
FROM `appointments`
  INNER JOIN 'line_items' ON 'line_items'.'appointment_id' = 'appointments'.'id'

总结果应为(10 +(10 + 15))+(15 +(10 + 20))

目前我正在尝试此查询。但它没有用。

    $(document).("pageshow","#pageXXX",function(){
       alert("This is a test")
    })

最佳方法是什么? line_items.price之和或加入sum line_items.price的子查询。还是有另一个更好的解决方案?

提前致谢!

3 个答案:

答案 0 :(得分:2)

我认为你要找的是派生表中的SUM() GROUP BY,然后是带有join的{​​{1}}。这样的事情。

appointments

答案 1 :(得分:1)

这应该会给你你想要的东西,似乎你接近答案:

SELECT SUM(app.price + IFNULL(li.price,0)) AS total_sum
FROM appointments app
  LEFT JOIN 
  (Select appointment_id, Sum(price) price from line_items group by appointment_id) li on li.appointment_id = app.id

答案 2 :(得分:0)

试试这个

 SELECT appointments.id,(appointments.price + sum(line_items.price)) AS total_sum
 FROM appointments
 INNER JOIN line_items ON line_items.appointment_id = appointments.id
 group by appointments.id