假设我有下表。
mysql> desc items;
+---------------+------------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+------------------------+------+-----+---------+-------+
| item_value | int(11) | YES | | NULL | |
| item_quantity | smallint(5) | YES | | NULL | |
+---------------+------------------------+------+-----+---------+-------+
当前SQL语句对于数量为1的商品是简单的。
select sum(item_value) as total_value from items where user_id = ?
如果一行的数量超过 1 个,我想在将所有用户的值相加时考虑到这一点。跟踪每行的总金额 (item_quantity
* item_value
) 是否更容易,或者我可以在 SQL 语句中完成吗?
最佳答案
您可以在 sum()
语句中进行算术运算:
select sum(item_quantity * item_value) as total_value from items where user_id = ?
关于mysql - 获取mysql中所有值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17689635/