[英]How can I multiply a result by a specific value from another table?
A simplification of my problem. 我的问题的简化。 Say I have these tables: 说我有这些表:
Supply: 供应:
Boxes: 盒:
Basically want I want to do is: 基本上我想做的是:
SELECT supplyName, numberOfSupply GROUP BY supplyName
from these tables. 从这些表。 But I want numberOfSupply to be quantityPerBox*numBoxes. 但我希望numberOfSupply是quantityPerBox * numBoxes。
Can this be done as a query? 可以作为查询吗? Or would I need to store the quantities from the Supply table in a program in some language (PHP for instance) and do the calculations there? 还是我需要以某种语言(例如PHP)将“供应”表中的数量存储在程序中,并在那里进行计算? (Or is there really no benefit from doing the calculation as part of the query, even if it's possible?) (或者即使有可能,将计算作为查询的一部分真的没有好处吗?)
Thank you for your help in advance. 提前谢谢你的帮助。 It's appreciated. 感激不尽
This can certainly be done in a query without having to store that value separately, or using a different language: 当然,这可以在查询中完成,而不必分别存储该值或使用其他语言:
SELECT s.supplyName, s.quantityPerBox * b.numBoxes AS NumberOfSupply
FROM Supply AS s
INNER JOIN Boxes AS b ON s.supplyName = b.supplyName
You probably want to add SupplyId
to both tables though so you have an integer value to JOIN
on: more efficient than trying to JOIN
on a VARCHAR
field. 不过,您可能想将SupplyId
添加到两个表中,以便在JOIN
上具有一个整数值:比在VARCHAR
字段上尝试JOIN
效率更高。 Another benefit is that if you ever wanted to change the supplyName
of an item, you would not have to worry about foreign key issues when making that change if you were referencing tables by ID instead of a value within the table. 另一个好处是,如果您想更改supplyName
,则在更改时,如果您是通过ID而不是表中的值来引用表,则不必担心外键问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.