繁体   English   中英

如何在MySQL中生成大量唯一的随机数

[英]How to generate a big number of unique random numbers in MySQL

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

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之间的随机数。

让我们考虑一下:

  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

为什么要重新发明轮子? 存在许多生成随机数的库。 例如,查看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()));
        }
    }
}

如果您的目标是生成唯一的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()));
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM