获取两个表列的总和

时间:2019-03-20 20:16:18

标签: mysql sql database

我有三个桌子。我想编写一个查询来使用MySQL中的表计算每个订单的总处理成本。

create table orders(id integer, packaging varchar(100), delivery 
varchar(100));

create table packaging_cost_tbl(packaging_type varchar(100), packaging_cost 
integer);

create table delivery_cos_tbl(delivery_type varchar(100), delivery_cost 
integer);

insert into orders(id, packaging, delivery) values(1, "Large", "Fast"),(2, 
"Small", "Fast"), (3, "Large", "Express"), (4, "Medium", "Standard"), (5, 
"Fragile", "Express"), (6, "Medium", "Fast"), (7, "Medium", "Standard");

insert into packaging_cost_tbl(packaging_type, packaging_cost) 
values("Small", 2), ("Medium", 5), ("Large", 8), ("Fragile", 10);

insert into delivery_cost_tbl(delivery_type, delivery_cost) 
values("Standard", 3), ("Fast", 7), ("Express", 15);

enter image description here

我上面已经提到了为每个表创建表查询和数据插入查询。输出应为

  • 订单ID
  • 总处理成本(处理成本=包装成本+交付成本)

1 个答案:

答案 0 :(得分:0)

我要在另外两个表上加入orders表,并求和它们的费用:

SELECT id, packaging_cost + delivery_cost
FROM   orders o
JOIN   packaging_cost_tbl p ON o.pacakging = p.packaging_type
JOIN   delivery_cost_tbl d ON o.delivery = d.delivery_type