MySQL汇总其他表

时间:2017-11-05 11:24:38

标签: mysql

我有以下表格:

产品:

id | price

发票:

id | product_id | amount | total

总计应包含产品价格乘以其金额。 例如:

产品:

1 | 3.00

发票:

1 | 1 | 5 | 15.00

我试图通过键入以下内容来填充总列:

SELECT product_id, amount, (amount * SELECT price from products WHERE id=product_id) as 'total' FROM invoice;

它不起作用。我的问题是,如何在列总数中增加产品价值?

2 个答案:

答案 0 :(得分:0)

您只需要INNER JOIN

SELECT *, (Products.price * amount) as total
FROM Invoice INNER JOIN Products
ON Invoice.id = Products.id 

答案 1 :(得分:0)

使用内部查询(你只是放错了括号)。

SELECT product_id, amount, amount * (SELECT price from products WHERE id=product_id) as 'total' FROM invoice;

或使用JOIN

SELECT product_id, amount, amount*price as 'total' from invoice inner join products on invoice.product_id=products.id

更新发票表中的总列数:

update invoice set total=amount*(select price from products where id=product_id);