问题描述
我需要一个 sql 查询来从我的消息队列中选择行,直到 SUM(users_count) 最多达到 1000.但是如果只返回一行并且该行的 users_count 为大于 1000.
I need a sql query to select rows from my messages queue, until SUM(users_count) reaches at most 1000. BUT there is no problem if there be only one row returned and that row's users_count is greater than 1000.
我需要类似的东西:(我添加了自己的关键字)
I need something like: (i added my own keywords)
SELECT * FROM `messages_queue` UNTIL SUM(users_count) < 1000 AT LEAST 1 ROW
这是我的表结构:
messages_queue
- msg_id
- msg_body
- users_count(消息接收者的数量)
- 时间(插入时间)
messages_queue
- msg_id
- msg_body
- users_count (number of message recieptors)
- time (insert time)
推荐答案
这个方案会进行累加,当总和超过1000时停止:
This solution will perform a cumulative sum, stopping when the sum exceeds 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
变量.
That means that if you have two values of, say, 800, the sum total will be 1600. The first SELECT is just to initialise the @total
variable.
如果你想防止总和超过 1000,除了单行的值大于 1000 的情况外,我认为这是可行的,尽管你需要对其进行一些严格的测试:
If you want to prevent the sum from exceeding 1000, apart from in cases where a single row has a value of greater than 1000, then I think this works, although you'll need to subject it to some rigorous testing:
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);
这篇关于要选择的 SQL 查询,直到 SUM(users_count) 达到 1000的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!