我需要一个SQL查询来从消息队列中选择行,直到SUM(users_count)最多达到1000。 但是 ,如果仅返回一行并且该行的users_count大于1000,就没有问题。
我需要类似的内容:(我添加了自己的关键字)
SELECT * FROM `messages_queue` UNTIL SUM(users_count) < 1000 AT LEAST 1 ROW
这是我的表结构:
messages_queue -msg_id -msg_body-users_count (消息接收方的数量) -时间(插入时间)
该解决方案将执行累积和,并在超过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变量。
@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);