如何在不重复的情况下显示数据库中的随机数。 [英] How to show the random number from database without repetition .

查看:61
本文介绍了如何在不重复的情况下显示数据库中的随机数。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据库中,我存储了500条记录,其主键是ID(数字)

现在我想随机显示用户的记录而不重复。根据我的要求每个用户我将显示一个id随机生成而不重复..

In my database i had stored 500 records its primary key is ID(number)
Now i want to show the record for user randomly without repetition.As per my requirement each user i will show one id randomly generaed without repetition..

推荐答案

创建一个ID数组,然后将数组洗牌。

查看我的解决方案: 纸牌游戏(在主要游戏中制作随机4组数字)组) [ ^ ]用于改组。

以随机顺序显示记录。

一旦出现,不要重复使用记录。

再次为下一系列记录洗牌。





首先得到一个记录对象的数组(或只是ID)。称之为 orderedData

调用 var shuffledData = Shuffle(orderedData); (见下文) )

按顺序使用 shuffledData [ 0到结束] 的值,它将成为记录对象(或如上所述的ID,没有重复的随机顺序。



Shuffle()的代码转换为通用:

Make an array of the IDs and then shuffle the array.
Look at my solution in: playing cards game (make Random 4 groups of Numbers in Main Group)[^] for shuffling.
Present the records in the shuffled order.
Don't re-use a record, once presented.
Shuffle again for the next sequence of records.


First get an array of the record objects (or just the IDs). Call it orderedData.
Call var shuffledData = Shuffle(orderedData); (see below)
Use the values of shuffledData[0 thru end] in sequence and it will be the record objects (or IDs, as above) in a random order with no repeats.

Code for Shuffle() converted to generic:
private Random rand = new Random();
public static T[] Shuffle<T>(T[] data)
{
  T[] shuffled = new T[data.Length];
  shuffled[0] = data[0];
  for (int i = 1; i < data.Length; i++)
  {
    int j = rand.Next(i + 1);
    if (j != i)
      shuffled[i] = shuffled[j];
    shuffled[j] = data[i];
  }
  return shuffled;
}



:我在Shuffle方法之外重命名了这个变量,所以不会混淆名称。


: I renamed the variable outside of the Shuffle method so there's no confusion about names.


当然,它非常简单。



Sure, and its quite easy.

SELECT TOP 1 * FROM table ORDER BY NEWID()





希望我能得到信任,但答案来自 Stack Overflow [ ^ ]



Hogan



Wish I could take credit, but the answer comes from Stack Overflow[^]

Hogan


您好,



参考



在循环中生成随机数而不重复。 [ ^ ]


这篇关于如何在不重复的情况下显示数据库中的随机数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆