在MySQL中选择每个都具有特定值的行组
假设我在表中有以下行:
+----+--------------+-------+------+ | ID | fruit | amount| price| +----+--------------+-------+------+ | 1 | oranges | 7 | 20 | +----+--------------+-------+------+ | 2 | plums | 21| 32 | +----+--------------+-------+------+ | 3 | oranges | 2 | 32 | +----+--------------+-------+------+ | 4 | oranges | 7 | 12 | +----+--------------+-------+------+ | 5 | plums | 4 | 89 | +----+--------------+-------+------+ | 6 | grapes | 5 | 34 | +----+--------------+-------+------+ | 7 | grapes | 6 | 132 | +----+--------------+-------+------+ | 8 | plums | 2 | 19 | +----+--------------+-------+------+
我的最终目标是在表格中获得每种独特水果的总金额和总价格。
现在,我想要达到预期效果的函数序列是:
using PHP: SELECT * from table where fruit = "oranges".
我将使用ajax来运行它,所以我将使用jquery来添加金额和价格。 然后重复“李子”和“葡萄”。
我将遇到的一个问题是我不知道水果桌上会有什么水果。
那么有没有一种更简单的方法可以在列中找到所有独特的水果,然后在数据库中搜索每个水果的行,然后为每个水果添加总计?
您还可以获取分组结果,然后迭代它以进行显示
select fruit, sum(amount), sum(amount*price) from table group by fruit