MySQL加入两个表并求和?

时间:2018-07-19 21:04:36

标签: mysql sql

enter image description here

我有2个表-ordersorderdetail

我需要将它们结合在一起并显示总数。我可以加入他们,但如何计算总数?

SELECT * 
FROM Orders as o 
INNER JOIN OrderDetails as od on o.order_id = od.order_id 
WHERE o.table_id = 1

1 个答案:

答案 0 :(得分:1)

 select a.order_id,
 order_date,
 order_status,
 table_id,
 item_id,
 item_price,
 quantity,
 b.item_price*b.quantity as total
 from dbo.orders as a inner join dbo.orderdetails as b
 on a.order_id=b.order_id
 WHERE table_id = 1
  

更新:如您在注释中提到的,如果您想要一个自动将数量和item_price相乘的计算列,则需要   执行此查询:

  ALTER TABLE dbo.orderdetails ADD Total AS (quantity* item_price);