mysql unique number generation

前端 未结 9 877
南笙
南笙 2020-12-05 03:17

I want to generate a unique random integer (from 10000 to 99999) identity just by clean mySQL; any ideas?

I don\'t want to generate this number in php by cycling (ge

相关标签:
9条回答
  • 2020-12-05 04:02

    I struggled with the solution here for a while and then realised it fails if the column has NULL entries. I reworked this with the following code;

    SELECT FLOOR(10000 + RAND() * 89999) AS my_tracker FROM Table1 WHERE "tracker" NOT IN (SELECT tracker FROM Table1 WHERE tracker IS NOT NULL) LIMIT 1
    

    Fiddle here; http://sqlfiddle.com/#!2/620de1/1

    Hope its helpful :)

    0 讨论(0)
  • 2020-12-05 04:02

    Create a unique index on the field you want the unique random #

    Then run

    Update IGNORE Table Set RandomUniqueIntegerField=FLOOR(RAND() * 1000000);

    0 讨论(0)
  • 2020-12-05 04:03

    I worry about why you want to do this, but you could simply use:

    SELECT FLOOR(RAND() * 1000000);
    

    See the full MySQL RAND documentation for more information.

    However, I hope you're not using this as a unique identifier (use an auto_increment attribute on a suitably large unsigned integer field if this is what you're after) and I have to wonder why you'd use MySQL for this and not a scripting language. What are you trying to achieve?

    0 讨论(0)
提交回复
热议问题