Inserting random characters to MYSQL Database

前端 未结 4 1296
说谎
说谎 2020-12-30 16:25

I want to add 100 entry to users table numbers field, random characters length is 10, all entry should be unique as well. How can i achieve this using MYSQL query code ?

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-30 17:12

    You can't generate an unique random number. Over time, the randomness will generate a number already stored. You need to make a "quasi-random" number, meaning that it's a number based on another data, but it just looks random. You can use the primary key on the table as the base number to generate the "fake-random" number

    INSERT INTO myTable(primaryKey,quasiRandom) 
        SELECT IFNULL(MAX(primaryKey),0)+1, CAST(CONCAT(IFNULL(MAX(primaryKey),0)+1,CHAR(FLOOR(RAND()*26)+65),FLOOR(100+RAND()*(500-100)))
     AS CHAR(10)) AS quasiRandom FROM myTable
    

提交回复
热议问题