Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.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
Mysql 选择具有某个累计值的行_Mysql_Sql - Fatal编程技术网

Mysql 选择具有某个累计值的行

Mysql 选择具有某个累计值的行,mysql,sql,Mysql,Sql,我有下表: -------------- | id | value | -------------- | 1 | 5 | -------------- | 2 | 2 | -------------- | 3 | 7 | -------------- | 4 | 8 | -------------- 我想找到按id排序的第一行,它将超过10的累计值。在这种情况下,它将是第3行,因为值列的5+2+7大于10 我该怎么做呢?假设您总是按id列排序,如果不按i

我有下表:

--------------
| id | value |
--------------
| 1  | 5     |
--------------
| 2  | 2     |
--------------
| 3  | 7     |
--------------
| 4  | 8     |
--------------
我想找到按id排序的第一行,它将超过10的累计值。在这种情况下,它将是第3行,因为值列的5+2+7大于10


我该怎么做呢?

假设您总是按id列排序,如果不按id列排序,则不可能按无序sql进行排序,那么这里有一个选项:

select *
from yourtable t
where exists (select 1 
              from yourtable t2
              where t2.id <= t.id
              having sum(value) > 10)
order by id
limit 1

可能最快的方法是使用变量:

select t.*
from (select t.*, (@s := @s + value) as sumv
      from t cross join
           (select @s := 0)
      order by id
     ) t
where sumv - value <= 10 and sumv > 10;