Mysql选择行的总和

时间:2012-08-13 10:46:35

标签: php mysql select sum

我有一张包含以下信息的表格:


id |      Item ID     | stock_package_id | amount | price
0  |        775       |         1        |   16   |  0.22
1  |        758       |         2        |   10   |  0.28
2  |        775       |         3        |   10   |  0.30
3  |        774       |         4        |   10   |  0.25
4  |        775       |         5        |   10   |  0.10
5  |        775       |         6        |   10   |  0.55


我的问题是我正在尝试创建一个查询(尽可能简单,因为这个表将与其他一些表保持联接),这将允许我输入一个数量:

e.g。

我想要首先从最便宜的价格中选择22个Item_Id 775。

所以我想要的是:


id |      Item ID     | stock_package_id | amount | price
4  |        775       |         5        |   10   |  0.10
0  |        775       |         1        |   12   |  0.22 - this is only 12 as we only want 22 total

一个pesudo例子:

从stock_table中选择,直到amount的总和等于或大于输入数字(22)按价格排序

这可能与MySql有关吗?

2 个答案:

答案 0 :(得分:5)

您需要使用ORDER BY子句根据price列对记录进行排序:

SELECT *
FROM table_name
WHERE Item_ID = 775
ORDER BY price ASC
LIMIT 22;

如果要在sum(price)成为value之前获取记录(22),请尝试以下操作:

SELECT *
FROM table_name, (SELECT @var_price := 0) a
WHERE Item_ID = 775 AND
      (@var_price := @var_price + price) <= 22
ORDER BY price ASC;

答案 1 :(得分:4)

架构:

 CREATE TABLE table1
(`id` int, `Item_ID` int, `stock_package_id` int, `amount` int, `price` float);

 INSERT INTO table1
(`id`, `Item_ID`, `stock_package_id`, `amount`, `price`)
 VALUES
(0, 775, 1, 16, 0.22),
(1, 758, 2, 10, 0.28),
(2, 775, 3, 10, 0.30),
(3, 774, 4, 10, 0.25),
(4, 775, 5, 10, 0.10),
(5, 775, 6, 10, 0.55);

设定金额:

SET @var_amount = 22;

选择金额:

SELECT * FROM (
SELECT table1.*, if ((@var_amount := @var_amount - amount) > 0, amount, amount +  @var_amount) as buy_amount
FROM table1
WHERE Item_ID = 775
ORDER BY price ASC
) AS tmp 
WHERE buy_amount > 0

结果:

id  Item_ID stock_package_id    amount  price   buy_amount
4   775 5                       10      0.1     10
0   775 1                       16      0.22    12