该解决方案将执行累积和,当总和超过1000时停止:
SELECT NULL AS users_count, NULL AS total
FROM dual
WHERE (@total := 0)
UNION
SELECT users_count, @total := @total + users_count AS total
FROM messages_queue
WHERE @total < 1000;
这意味着如果您有两个值(例如800),则总和将为1600.第一个SELECT只是初始化@total变量.
如果要防止总额超过1000,除了单排值大于1000的情况下,我认为这是有效的,虽然您需要进行严格的测试:
SELECT NULL AS users_count, NULL AS total, NULL AS found
FROM dual
WHERE (@total := 0 OR @found := 0)
UNION
SELECT users_count, @total AS total, @found := 1 AS found
FROM messages_queue
WHERE (@total := @total + users_count)
AND @total < 1000
UNION
SELECT users_count, users_count AS total, 0 AS found
FROM messages_queue
WHERE IF(@found = 0, @found := 1, 0);