You have a design flaw. Leave the auto increment alone and shuffle your query result (when you fetch your data)
MySql auto_increment plus a certain number
-
29-06-2023 - |
Question
I want my the id field in my table to be a bit more " random" then consecutive numbers.
Is there a way to insert something into the id field, like a +9, which will tell the db to take the current auto_increment value and add 9 to it?
Solution 2
OTHER TIPS
Though this is generally used to solve replication issues, you can set an increment value for auto_increment:
Since that is both a session and a global setting, you could simply set the session variable just prior to the insert.
Besides that, you can manually do it by getting the current value with MAX()
then add any number you want and insert that value. MySQL will let you know if you try to insert a duplicate value.
As far as i know, it's not possible to 'shuffle' your current IDs. If you wanted though, you could pursue non-linear IDs in the future.
The following is written in PDO, there are mysqli equivalents.
This is just an arbitrary INSERT
statement
$name = "Jack";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "INSERT INTO tableName (name) VALUES(:name)";
$q = $conn->prepare($sql);
$q->execute(':name' => $name);
Next, we use lastInsertId()
to return the ID of the last inserted row, then we concatenate the result to rand()
$lastID = $conn->lastInsertId();
$randomizer = $lastID.rand();
Finally, we use our 'shuffled' ID and UPDATE
the previously inserted record.
$sql = "UPDATE tableName SET ID = :randomizer WHERE ID=:lastID ";
$q = $conn->prepare($sql);
$q->execute(array(':lastID' => $lastID , ':randomizer' => $randomizer));
An idea.. (Not tested)
CREATE TRIGGER
'updateMyAutoIncrement'BEFORE INSERT
ON
'DatabaseName'.'TableName'FOR EACH ROW
BEGIN
DECLARE
aTmpValueHolderINT DEFAULT 0;
SELECT
AUTO_INCREMENT INTO
aTmpValueHolderFROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA =
'DatabaseName'AND TABLE_NAME =
'TableName';
SET NEW
.idColumnName=
aTmpValueHolder+ 9;
END
;
Edit : If the above trigger doesn't work try to update AUTO_INCREMENT
value directly into the system's schema. But as noted by Eric, your design seems to be flawed. I don't see the point of having an auto-increment here.
Edit 2 : For a more 'random' and less linear number.
SET NEW
.idColumnName=
aTmpValueHolder+ RAND(10);
Edit 3 : As pointed out by Jack Williams, Rand()
produces a float
value between 0 and 1.
So instead, to produce an integer, we need to use a floor function to transform the 'random' float into an integer.
SET NEW
.idColumnName =
aTmpValueHolder + FLOOR(a + RAND() * (b - a));
where a and b are the range of the random number.