[英]How to round robin by UUID in SQL database?
I have a list of agents that I want to assign tasks to using round robin.我有一个代理列表,我想将任务分配给使用循环法。
agents<\/code> table:
agents<\/code>表:
id ID<\/th><\/tr><\/thead> |
---|
uuid1 uuid1<\/td><\/tr> |
uuid2 uuid2<\/td><\/tr> |
uuid3 uuid3<\/td><\/tr> |
uuid4 uuid4<\/td><\/tr><\/tbody><\/table> How to get rows of the table above in a round robin fashion?如何以循环方式获取上面表格的行? Desired outcome:期望的结果: uuid1 -> uuid2 -> uuid3 -> uuid4 -> uuid1 (repeat) uuid1 -> uuid2 -> uuid3 -> uuid4 -> uuid1(重复) I tried ordering uuids then selecting the next one based on the previous uuid我尝试订购 uuid,然后根据前一个 uuid 选择下一个
|
select nxt
from (
select
-- for every id, find the next item, if not exists, use the earliest (min)
id, coalesce(lead(id) over (order by id),(select min(id) from Tbl)) as nxt
from Tbl
) as Agents
where id = 'uuid4'
I don't have PostgreSQL handy right now, but this works under SQL Server and I don't see an obvious reason why it shouldn't under any other DBMS:我现在手头没有 PostgreSQL,但这在 SQL Server 下有效,我看不出它不应该在任何其他 DBMS 下的明显原因:
COALESCE(
(SELECT TOP 1 id FROM agents WHERE @current_id < id ORDER BY id),
(SELECT TOP 1 id FROM agents ORDER BY id)
)
You can combine two queries where the second is only run if the first one didn't return anything:您可以组合两个查询,其中第二个查询仅在第一个查询未返回任何内容时运行:
with next_agent as (
SELECT id
FROM agents
WHERE id > $1 -- the last ID retrieved or NULL if it's the first
ORDER BY id
limit 1
)
select *
from next_agent
union all
select *
from agents
where not exists (select * from next_agent)
order by id
limit 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.