我有一个包含 1 列 id
的表。现在我想为我的表创建一个新列,所以我希望新列的数据被散列为 id
。像这样:
// my table
+------+
| id |
+------+
| 1 |
| 2 |
| 3 |
+------+
// I want this table
+------+------------+
| id | hashed |
+------+------------+
| 1 | 00320032 |
| 2 | 00330033 |
| 3 | 00340034 |
+------+------------+
需要注意的是,hashed
列是基于:
散列('adler32', '1');//输出:00320032
散列('adler32', '2');//输出:00330033
散列('adler32', '3');//输出: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;");
关于php - 如何创建一个新列包含 id 列的散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31397091/