jeudi 24 septembre 2015

Insert random string into field with MySQL UNI key

The task is to fill the table with N rows of random unique data.

I have the next MySQL table structure:

+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| username | varchar(100) | NO   | UNI | NULL    |                |
+----------+--------------+------+-----+---------+----------------+

Username field has string type but if the script will insert numbers its OK.

Theres is dirty solution with INSERT IGNORE, that can make 1000 random rows with endless cycle.

INSERT IGNORE INTO table (id,username) VALUES ('', 1 + ceil(rand() * 1000));

Also, I can use ON DUPLICATE KEY structure, but this 2 solutions are not OK.

I want to make the query, that generate unique username which will be unique and will be inserted from the first time.

So, I tell the script to add 1m of rows and it will insert 1m of unique data without any infelicities.

Any ideas? Thanks.




Aucun commentaire:

Enregistrer un commentaire