Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php SQL:如何选择总和为特定值的行_Php_Mysql_Sql_Sum - Fatal编程技术网

Php SQL:如何选择总和为特定值的行

Php SQL:如何选择总和为特定值的行,php,mysql,sql,sum,Php,Mysql,Sql,Sum,我想选择总和为某个值的行 我的SQL(): 它应该将总和计算为410000,并得到行数。同时,它应该是这样的: id user_id storage 2 1 42552 3 1 367225 如您所见,42552+367225=409777。它选择了近410000行 我什么都试过了,但都没用:( 对不起,我的语言是德语。这是您需要的: SET @suma = 0; SELECT @suma:=@suma+`storage`, id, s

我想选择总和为某个值的行

我的SQL():

它应该将总和计算为410000,并得到行数。同时,它应该是这样的:

id  user_id     storage
2   1           42552
3   1           367225
如您所见,42552+367225=409777。它选择了近410000行

我什么都试过了,但都没用:(

对不起,我的语言是德语。

这是您需要的:

SET @suma = 0;
SELECT @suma:=@suma+`storage`, id, storage FROM table 
WHERE @suma<=410000 
ORDER BY storage ASC;
SET@suma=0;
从表中选择@suma:=@suma+`storage`,id,storage

其中@suma可以使用相关子查询来获取运行总数,并检索运行总数小于指定数字的行。(注意,我将存储列更改为
int
。如果是
varchar
,比较将返回错误的结果)


对于php,这将是微不足道的。您想要一个仅mysql的解决方案吗?似乎您对StackOverflow还比较陌生。如果答案对您有帮助,请务必投票支持。如果答案解决了您的问题,请将答案标记为已接受。@GeorgePant否,php会更好:)这似乎可以通过动态编程或回溯来更好地解决。
我尝试了所有方法,但都没有成功:(
我不确定,真的所有方法都有效吗?人们应该相信吗?:D请大家看一看。与其说出来,不如说每个人都应该展示(代码)已尝试的内容当这些行的值相等时,您只需选择其中一行。在这种情况下,请在用户id和存储上使用
分组依据
。但是,在其他情况下,这也会是一个问题。我会解决它。请查看编辑的版本,它不需要
分组依据
SET @suma = 0;
SELECT @suma:=@suma+`storage`, id, storage FROM table 
WHERE @suma<=410000 
ORDER BY storage ASC;
select id,user_id,storage
from uploads t
where storage+coalesce((select sum(storage) from uploads 
                        where storage<t.storage),0) < 410000
order by storage
select id,user_id,storage
from uploads t
where storage+coalesce((select sum(storage) from uploads 
                        where storage<t.storage 
                        or (storage=t.storage and id < t.id)),0) < 410000
order by storage