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?

有帮助吗?

解决方案 2

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:

auto_increment_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)

  1. CREATE TRIGGER 'updateMyAutoIncrement'
  2. BEFORE INSERT
  3. ON 'DatabaseName'.'TableName'
  4. FOR EACH ROW
  5. BEGIN
  6. DECLARE aTmpValueHolder INT DEFAULT 0;
  7. SELECT AUTO_INCREMENT INTO aTmpValueHolder
  8. FROM INFORMATION_SCHEMA.TABLES
  9. WHERE TABLE_SCHEMA = 'DatabaseName'
  10. AND TABLE_NAME = 'TableName';
  11. SET NEW.idColumnName =aTmpValueHolder + 9;
  12. 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.

  1. 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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top