0

I'm building the following query:

SELECT taskid
FROM tasks, (SELECT @var_sum := 0) a
WHERE (@var_sum := @var_sum + taskid) < 10

Result:

taskid
1
2
3

Right now it's returning me all rows that when summed are <10, I want to include one extra row to my result (10 can be anything though, it's just an example value)

So, desired result:

taskid
1
2
3
4
4

3 回答 3

1

If you want the first value that is ">= 10":

SELECT taskid
FROM tasks, (SELECT @var_sum := 0) a
WHERE (@var_sum < 10) or (@var_sum < 10 and @var_sum := @var_sum + taskid) >= 10);

Although this will (probably) work in practice, I don't think it is guaranteed to work. MySQL does not specify the order of evaluation for where clauses.

EDIT:

This should work:

select taskid
from (SELECT taskid, (@var_sum := @var_sum + taskid) as varsum
      FROM tasks t cross join
           (SELECT @var_sum := 0) const
    ) t
WHERE (varsum < 10) or (varsum - taskid < 10 and varsum >= 10);
于 2013-08-23T16:31:36.427 回答
1

I would do it like this:

SELECT t.taskid
  FROM tasks t 
 CROSS
  JOIN (SELECT @var_sum := 0) a
 WHERE IF(@var_sum<10, @var_sum := @var_sum+t.taskid, @var_sum := NULL) IS NOT NULL

This is checking if the current value of @var_sum is less than 10 (or less than whatever, or less than or equal to whatever. If it is, we add the taskid value to @var_num, and the row is included in the resultset. But when the current value of @var_sum doesn't meet the condition, we assign a NULL to it, and the row does not get included.

NOTE The order of rows returned from the tasks table is not guaranteed. MySQL can return the rows in any order; it may look deterministic in your testing, but that's likely because MySQL is choosing the same access plan against the same data.

于 2013-08-23T17:56:53.527 回答
0

To add an extra row use UNION ALL then code what you want for the extra row:

SELECT taskid
FROM tasks, (SELECT @var_sum := 0) a
WHERE (@var_sum := @var_sum + taskid) < 10
UNION ALL
SELECT 4

Because you haven't said how you derive the extra riw, I have coded a constant value, but you can change it to whatever you need.

于 2013-08-23T16:41:13.197 回答