为表中的主键随机生成1-999之间的唯一数字 [英] randomly generating unique number between 1-999 for primary key in table
问题描述
我有一个问题,我不确定如何优雅地解决.
I have a problem I'm not sure how to solve elegantly.
背景信息
我有一个小部件表.每个小部件都从一系列数字(例如1-999之间)中分配了一个ID. 1-999的值在名为"config"的表中保存为"lower_range"和"upper_range". 当用户请求使用我的Web应用程序创建新的窗口小部件时,我需要执行以下操作:
I have a table of widgets. Each widget is assigned an ID from a range of numbers, let's say between 1-999. The values of 1-999 is saved in my database as "lower_range" and "upper_range" in a table called "config". When a user requests to create a new widget using my web app, I need to be able to do the following:
- 使用lua的math.random函数或sqlite中的随机数生成器生成1到999之间的随机数(到目前为止,在我的测试中,lua的math.random始终返回相同的值...但这是不同的问题)
- 执行一条select语句,看看是否已经有一个分配了该编号的小部件...
- 如果没有,请创建新的窗口小部件.
- 否则,请重复此过程,直到获得当前未使用的号码.
问题
我发现上述逻辑有两个问题:
The problem I see with the above logic is two-fold:
- 该算法可能会花费很长时间,因为我必须不断搜索直到找到唯一的值.
- 如何防止同时请求新的小部件编号产生相同的值?
任何建议将不胜感激. 谢谢
Any suggestions would be appreciated. Thanks
推荐答案
提前生成您的随机数并将其存储在表格中;确保数字是唯一的.然后,当您需要获取下一个号码时,只需检查已经分配了多少个号码,然后从表格中获取下一个号码即可.所以,而不是
Generate your random numbers ahead of time and store them in a table; make sure the numbers are unique. Then when you need to get the next number, just check how many have already been assigned and get the next number from your table. So, instead of
- 生成介于1-999之间的数字
- 检查是否已分配
- 生成新号码,依此类推.
执行以下操作:
- 生成999个元素的数组,其随机顺序的值是1-999
- 您的
GetNextId
功能变为return ids[currentMaxId+1]
- Generate array of 999 elements that have values 1-999 in some random order
- Your
GetNextId
function becomesreturn ids[currentMaxId+1]
要管理同时发生的请求,您需要具有一些生成适当序列的资源.最简单的方法可能是将窗口小部件表中的键用作ids
数组中的索引.因此,首先将记录添加到widgets
表中,获取其键,然后使用ids[key]
生成小部件ID.
To manage simultaneous requests, you need to have some resource that generates a proper sequence. The easiest is probably to use a key in your widget table as the index in the ids
array. So, add a record to the widgets
table first, get its key and then generate widget ID using ids[key]
.
这篇关于为表中的主键随机生成1-999之间的唯一数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!