Last active
October 12, 2020 13:15
-
-
Save pmn4/00470c14675c98e438301a3475084fa6 to your computer and use it in GitHub Desktop.
Create new Records with Unique Randomized Token using a Single Query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Insert into table with a unique token column without a loop | |
| # using `LEFT(UUID(), 8)` as the unique string generator for simplicity, | |
| # feel free to use whatever method you'd like, including generating those | |
| # in memory and putting raw strings into your query | |
| INSERT INTO table(column1, column2, token_column) | |
| SELECT "column1_value", "column2_value", token FROM ( | |
| # create a derived table containing five (feel free to increase) | |
| # potential unique strings | |
| SELECT LEFT(UUID(), 8) as token | |
| UNION SELECT LEFT(UUID(), 8) | |
| UNION SELECT LEFT(UUID(), 8) | |
| UNION SELECT LEFT(UUID(), 8) | |
| UNION SELECT LEFT(UUID(), 8) | |
| ) as tokens | |
| WHERE NOT EXISTS ( | |
| SELECT 1 | |
| FROM table | |
| WHERE token_column = tokens.token | |
| ) | |
| LIMIT 1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you may need to convert the unique string, i.e.,
(assumes the token column is defined as latin1)