从大型mysql db中的另一个表更新列(700万行)

时间:2012-07-11 10:11:54

标签: mysql large-data-volumes

描述

我有2个具有以下结构的表(删除了不相关的列):

mysql> explain parts;
+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| code        | varchar(32)  | NO   | PRI | NULL    |       |
| slug        | varchar(255) | YES  |     | NULL    |       |
| title       | varchar(64)  | YES  |     | NULL    |       |
+-------------+--------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

mysql> explain details;
+-------------------+--------------+------+-----+---------+-------+
| Field             | Type         | Null | Key | Default | Extra |
+-------------------+--------------+------+-----+---------+-------+
| sku               | varchar(32)  | NO   | PRI | NULL    |       |
| description       | varchar(700) | YES  |     | NULL    |       |
| part_code         | varchar(32)  | NO   | PRI |         |       |
+-------------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

parts包含184147行,details包含7278870行。 part_code中的details列代表code表中的parts列。 由于这些列为varchar,因此我希望将列id int(11)添加到parts,将part_id int(11)添加到details。我试过这个:

mysql> alter table parts drop primary key;
Query OK, 184147 rows affected (0.66 sec)
Records: 184147  Duplicates: 0  Warnings: 0

mysql> alter table parts add column
       id int(11) not null auto_increment primary key first;
Query OK, 184147 rows affected (0.55 sec)
Records: 184147  Duplicates: 0  Warnings: 0

mysql> select id, code from parts limit 5;
+----+-------------------------+
| id | code                    |
+----+-------------------------+
|  1 | Yhk0KqSMeLcfH1KEfykihQ2 |
|  2 | IMl4iweZdmrBGvSUCtMCJA2 |
|  3 | rAKZUDj1WOnbkX_8S8mNbw2 |
|  4 | rV09rJ3X33-MPiNRcPTAwA2 |
|  5 | LPyIa_M_TOZ8655u1Ls5mA2 |
+----+-------------------------+
5 rows in set (0.00 sec)

所以现在我在parts表中有正确数据的id列。将part_id列添加到details表后:

mysql> alter table details add column part_id int(11) not null after part_code;
Query OK, 7278870 rows affected (1 min 17.74 sec)
Records: 7278870  Duplicates: 0  Warnings: 0

现在最大的问题是如何相应地更新part_id?以下查询:

mysql> update details d
       join parts p on d.part_code = p.code
       set d.part_id = p.id;

跑了大约30个小时,直到我杀了它。

请注意,这两个表都是MyISAM:

mysql> select engine from information_schema.tables where table_schema = 'db_name' and (table_name = 'parts' or table_name = 'details');
+--------+
| ENGINE |
+--------+
| MyISAM |
| MyISAM |
+--------+
2 rows in set (0.01 sec)

我刚刚意识到其中一个问题是删除parts表上的密钥我将索引放在code列上。另一方面,我在details表上有以下索引(省略了一些不相关的列):

mysql> show indexes from details;
+---------+------------+----------+--------------+-------------+-----------+-------------+------------+
| Table   | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Index_type |
+---------+------------+----------+--------------+-------------+-----------+-------------+------------+
| details |          0 | PRIMARY  |            1 | sku         | A         |        NULL | BTREE      |
| details |          0 | PRIMARY  |            3 | part_code   | A         |     7278870 | BTREE      |
+---------+------------+----------+--------------+-------------+-----------+-------------+------------+
2 rows in set (0.00 sec)

我的问题是:

  1. 更新查询是否正常,或者可以某种方式对其进行优化?
  2. 我会在code表的parts列中添加索引,查询是否会在合理的时间内运行,还是会再运行几天?
  3. 如何创建(sql / bash / php)脚本以便查看查询执行的进度?
  4. 非常感谢!

3 个答案:

答案 0 :(得分:4)

正如我在问题中提到的,我忘记了parts表上删除的索引,所以我添加了它们:

alter table parts add key code (code);

受到Puggan Se答案的启发,我尝试在PHP脚本中使用LIMIT上的UPDATE,但LIMIT不能与UPDATE一起使用JOIN在MySQL中{1}}。为了限制查询,我在details表中添加了一个新列:

# drop the primary key,
alter table details drop primary key;
# so I can create an auto_increment column
alter table details add id int not null auto_increment primary key;
# alter the id column and remove the auto_increment
alter table details change id id int not null;
# drop again the primary key
alter table details drop primary key;
# add new indexes
alter table details add primary key ( id, sku, num, part_code );

现在我可以使用“限制”:

update details d
join parts p on d.part_code = p.code
set d.part_id = p.id
where d.id between 1 and 5000;

所以这是完整的PHP脚本:

$started = time();
$i = 0;
$total = 7278870;

echo "Started at " . date('H:i:s', $started) . PHP_EOL;

function timef($s){
    $h = round($s / 3600);
    $h = str_pad($h, 2, '0', STR_PAD_LEFT);
    $s = $s % 3600;
    $m = round( $s / 60);
    $m = str_pad($m, 2, '0', STR_PAD_LEFT);
    $s = $s % 60;
    $s = str_pad($s, 2, '0', STR_PAD_LEFT);
    return "$h:$m:$s";
}

while (1){
    $i++;
    $j = $i * 5000;
    $k = $j + 4999;
    $result = mysql_query("
        update details d
        join parts p on d.part_code = p.code
        set d.part_id = p.id
        where d.id between $j and $k
    ");
    if(!$result) die(mysql_error());
    if(mysql_affected_rows() == 0) die(PHP_EOL . 'Done!');
    $p = round(($i * 5000) / $total, 4) * 100;
    $s = time() - $started;
    $ela = timef($s);
    $eta = timef( (( $s / $p ) * 100) - $s );
    $eq = floor($p/10);
    $show_gt = ($p == 100);
    $spaces = $show_gt ? 9 - $eq : 10 - $eq;
    echo "\r {$p}% | [" . str_repeat('=', $eq) . ( $show_gt ? '' : '>' ) . str_repeat(' ', $spaces) . "] | Elapsed: ${ela} | ETA: ${eta}";
}

这是截图:

working script screenshot

正如你所看到的,整件事花了不到5分钟:) 谢谢大家!

P.S。:还有一个错误,因为我后来发现part_id = 0剩下4999行,但我已经手动完成了。

答案 1 :(得分:1)

  1. 您可能想要添加位置和限制,以便以块的形式更新

    update details d
    join parts p on d.part_code = p.code
    set d.part_id = p.id
    WHERE d.part_id =0
    LIMIT 5000;
    
  2. 它会有更快的whit索引,如果你在上面的'1'中执行一个sugesten的查询,你可以查看5000行需要多长时间来处理

  3. 循环查询

    while(TRUE)
    {
        $result = mysql_query($query);
        if(!$result) die('Failed: ' . mysql_error());
        if(mysql_affected_rows() == 0) die('Done');
        echo '.';
    }
    
  4. 编辑1 重写查询do以限制连接错误

    您可以使用子查询来避免多个表更新:

    UPDATE details
    SET part_id = (SELECT id FROM parts WHERE parts.code = details.part_code)
    WHERE part_id = 0
    LIMIT 5000;
    

答案 2 :(得分:0)

您可以尝试从您尝试更新的表中删除索引。 MySQL在每行更新时重新创建索引。对于7M记录来说,它不会很快。