我需要简单的选择查询。在条件i中,我传递了一个值,当金额之和大于该值时,则返回。如果我通过4,则返回2行(在图片ID-> 125,126 中),因为该2行的总和(金额)是10,大于4。
输入
输出
通过该查询可以正常工作
SET @total:=0.0;
SELECT id,
amount,
price,
@total := @total + Truncate((amount), 8) AS total_offers
FROM table
WHERE @total < 4;
如果我使用订单,则无法使用
SET @total:=0.0;
SELECT id,
amount,
price,
@total := @total + Truncate((amount), 8) AS total_offers
FROM table
WHERE @total < 4
ORDER BY price DESC;
我现在需要如何解决此问题的订单
答案 0 :(得分:1)
我认为它应该对您有用。
set @total:=0.0;
SELECT temp.id, temp.amount, temp.price,
@total := @total + Truncate(amount, 8) AS total_offers from (
SELECT temp.* FROM table temp ORDER BY price DESC
) temp
where @total < 4
答案 1 :(得分:0)
我认为自MySQL 5.6起,使用变量时,您需要在子查询中执行order by
。因此,这应该可行:
SELECT id, amount, price, total_offers
FROM (SELECT t.id, t.amount, t.price,
@total := @total + Truncate(amount, 8) AS total_offers
FROM (SELECT t.*
FROM table t
ORDER BY price DESC
) t CROSS JOIN
(SELECT @total := 0) params
) t
WHERE total_offers < 4;
请注意,这还将更改比较以使用该变量。 WHERE
子句中变量的求值也是不确定的。
在MySQL 8.0中,这更简单地写为:
select t.*
from (select t.*,
sum(amount) over (order by price desc) as total_amount
from table
) t
where total_amount < 4;