如何创建一个包含id列散列的新列


how to create a new column contained the hash of id column

我有一个包含1列id的表。现在我想为我的表创建一个新列,所以我想将新列的数据散列为id。像这样的东西:

// my table
+------+
|  id  |
+------+
|  1   |
|  2   |
|  3   |
+------+
// I want this table
+------+------------+
|  id  |   hashed   |
+------+------------+
|  1   |  00320032  |
|  2   |  00330033  |
|  3   |  00340034  |
+------+------------+

需要注意的是,hashed列基于:

hash('adler32', '1'); // output: 00320032

hash('adler32', '2'); // output: 00330033

hash('adler32', '3'); // output: 00340034

现在,我可以那样做吗?

在其他可能的方法中,您可以首先获取所有id,计算其中每一个的哈希值,然后将数据重新插入表中(并避免重复:(

以下是感兴趣的(没有进行错误检查:(

<?php
// Adding the column named 'hashed'
$mysqli->query('ALTER TABLE your_table ADD COLUMN (`hashed` INT);');
// Retrieving all the 'id's
$result = $mysqli->query('SELECT id FROM your_table;');
$IDs = $result->fetch_all(MYSQLI_ASSOC);
$result->close();
// Assembling the values for a bulk INSERT statement
$values = array();
foreach($IDs as $row) {
    $ID = $row['id'];
    $hashed = hash('adler32', $ID);
    $values[] = "($ID, $hashed)";
}
$values = implode(',', $values);
// Delete to avoid duplicates
$mysqli->query("DELETE FROM your_table;");
// Insert the 'id's and their respective hashed values
$mysqli->query("INSERT INTO your_table (id, hashed) VALUES $values;");