【问题标题】:How to generate a big number of unique random numbers in MySQL如何在 MySQL 中生成大量唯一随机数
【发布时间】:2014-09-10 05:47:08
【问题描述】:

在我的项目中,我需要生成大量(数千个)唯一随机数。到目前为止,我正在使用这个效率不高的解决方案:

public void codeFactory(int count) {
    for (;count > 0; count --) {
        while (true) {
            long code = getRandomCode();
            Long codeStored = em.select("c.code").from("codes c").where("c.code = ?", code)
                .fetchSingle(Long.class);
            if (codeStored == null) {
                // this code has not yet been stored
                break;
            } else {
                // we continue, this code is already stored
                continue;
            }
            ...
        }
        // we have created a unique code
    }
}

有没有办法直接用 MySQL 创建它们,这样我就不需要为每个代码访问 MySQL?

编辑: 我想生成介于 1000000000000 和 9999999999999 之间的随机数。

【问题讨论】:

  • 所有数据库都可以生成增量索引,查看mysql的auto_increment
  • “大量的唯一随机数”...这到底是什么意思?比如:你想生成1000个0到1之间的随机数吗?
  • 你看过rand()吗?
  • 我想生成介于 1000000000000 和 9999999999999 之间的 RANDOM 和 UNIQUE 数字。

标签: java mysql


【解决方案1】:

让我们考虑一下:

  1. 您的表名为TestTable
  2. 你必须在两个数字min_nummax_number之间生成一个随机数
  3. 随机数应该是唯一的并且将存储在TestColumn列中

你可以这样做

SELECT FLOOR(RAND() * (<max_number> - <min_num> + 1)) + <min_number> AS random_number
FROM TestTable 
WHERE "random_num" NOT IN (SELECT TestColumn FROM TestTable) LIMIT 1

【讨论】:

  • 到目前为止最好的答案,会等着看是否还有更多,但我可能会接受这个。
【解决方案2】:

为什么要重新发明轮子?存在许多库来生成随机数。以 apache.commons.math3 为例:

package com.techtrip.labs.stackoverflow;

import org.apache.commons.math3.random.ISAACRandom;

public class GeneralTest {
    public static void main(String[] args) {        
        int[] seed = {19399213, 123219, 32132, 32838};
        ISAACRandom rndGen = new ISAACRandom(seed);
        for (int i = 0; i < 1000; i++){
            System.out.println(String.format("The random value is %d", rndGen.nextLong()));
        }
    }
}

【讨论】:

  • 这与MySQL和我的问题无关。
  • 我在重读您的描述后意识到,这就是我提供 JPA 解决方案的原因。但是,您对问题的描述令人困惑,因此其他人的 cmets 以及您在对问题陈述的编辑中进行了澄清。声明“有没有办法直接使用 MySQL 创建它们,这样我就不需要为每个代码访问 MySQL?”完全没有意义。但是,如果您正在寻找一种在 MySql 中生成随机数的方法,尽管上面 Hitesh 的答案很好。
【解决方案3】:

如果您的目标是生成唯一 id,您也可以使用 JPA 和序列生成器进行通用操作;有很多策略。

例如,非常简单:

@MappedSuperclass
public abstract class AbstractEntity {

    /** The id. */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    protected Long id;

    /**
     * @return the id
     */
    public Long getId() {
        return id;
    }

    @Override
    public int hashCode() {
..
    }

    @Override
    public boolean equals(Object obj) {
...
    }

@Entity
@Table(name = "Something")
public class Something extends AbstractEntity {
... // rest of Something Body
}

public interface SomethingRepository extends CrudRepository<Something, Long>{

}

// Simple test using initializing bean 
@Component
public class SomethingTest implements InitializingBean {
    @Autowired
    SomethingRepository sRepo;

    @Override
    @Transactional
    public void afterPropertiesSet() throws Exception {
        for (int i = 1; i < 10; i++) {
            sRepo.save(new Something());
        }

        Iterator<Something> i = sRepo.findAll().iterator();

        while(i.hasNext()) {
            Something s = i.next();
            System.out.println(String.format("Next random sequence num %d", s.getId()));
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多