来自不同表格的单元格总和

时间:2018-01-20 14:07:42

标签: mysql sql

我有一张桌子'价格'看起来像:

itemId, name, price, cover
1, Book, 30, paper
2, Phone, 100, box
3, Flower, 10, paper

并有第二个表'cover'看起来像:

coverId, cover, price
1, paper, 5
2, box, 10

我如何才能获得退回物品只有纸盖的附加颜色为SUM(商品价格+封面价格)按SUM(商品价格+封面价格)订购,如下:

itemId, name, priceOfItemPluspriceOfCover
3, flower, 15
1, book, 35 

谢谢你们!

2 个答案:

答案 0 :(得分:2)

简单inner join将起作用

select p.itemId, p.name, p.price+c.price 
from price p 
inner join covers c on p.cover = c.cover 
Where c.cover = 'paper'

我建议您将coverid存储在价格表而不是封面名称中,并定义外键以保持数据完整性

答案 1 :(得分:2)

select price.itemid, price.name, sum(price.price, covers.price) as priceOfItemPluspriceOfCover from price inner join covers on price.cover = covers.cover