【问题标题】:how to create a new column contained the hash of id column如何创建一个包含 id 列哈希的新列
【发布时间】:2015-10-02 12:39:32
【问题描述】:

我有一个包含 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

现在,我可以这样做吗?

【问题讨论】:

  • hashed 是否已经存在?为什么不在hash() 函数中使用SELECT last_insert_id() 作为第二个参数?
  • hashed 列不存在,但这不是问题,我可以创建它。我想在其中插入id 的哈希。
  • 您可以将散列值分配给一个变量,然后在插入语句中使用该变量吗? $hashed = hash('adler32', '1'); 然后mysql_query("INSERT INTO your_table_name (id, hashed) VALUES (null, $hashed)");??
  • @ride_85027 emm,还不错,谢谢
  • 我会添加作为未来读者的答案。告诉我它是如何工作的!

标签: php mysql sql hash


【解决方案1】:

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

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

<?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;");

【讨论】:

    猜你喜欢
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多