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?
You have a design flaw. Leave the auto increment alone and shuffle your query result (when you fetch your data)
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.
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
aTmpValueHolder INT DEFAULT 0;
SELECT
AUTO_INCREMENT INTO
aTmpValueHolder FROM 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.