【问题标题】:Issues with selecting rows from large tables and updating them从大表中选择行并更新它们的问题
【发布时间】:2017-04-19 03:02:19
【问题描述】:

我一共有 7 张桌子。其中 1 个将用作与其他 6 个的比较,它将从其他 5 个更新列。就列不多而言,主表总共有 17 个列。但是行,该主表大约有 66,000 行。现在我一直在做一些研究并将表设置为 MISAM 而不是 InnoDB,但加载速度没有太大变化。所以这是我最初的方法:

  1. 从表 1 中选择所有行,然后在 PHP 中执行 foreach 行获取某些列值,并对其他 6 个表中的每一个执行特定选择以返回单个值:

    $all = $table1->selectAll();
    foreach( $all as $a_template ){
          $id = $a_template['id'];
    
          $table2 = new Table2();
          $table3 = new Table3();
          $table4 = new Table4();
          $table5 = new Table5();
          $table6 = new Table6();
    
          $table2->select($a_template['column1']);
          $table3->select($a_template['column2']);
          $table4->select($a_template['column3']);
          $table5->select($a_template['column4']);
          $table6->selectByCode($a_template['npsecondarycode']);
    
          $table1 = new Table1();
          $table1->update($table2->getColumnVal(), $table3->getColumnVal(), $table4->getColumnVal(), $table5->getColumnVal(), $table6->getColumnVal(), $id);
    
        }
    

调用“getColumnVal()”的函数只是返回执行选择时设置的值,没什么大不了的。

现在这个过程大约需要 15 到 20 分钟来处理 66,000 条记录,而且我无法再加快它的速度,在某些情况下会导致内存问题,我不得不将内存限制升级到 1GB至少。

我确实尝试过直接通过 MySQL 并使用内部连接进行选择,因为我听说数据库可以使用更大的数据和更快的速度进行更密集的查询,但在这种情况下它实际上会锁定并停止一起工作,在某些情况下,PhpMyAdmin 会给我一个 500 错误。

我不确定从这里走哪条路,因为我以前从未遇到过这种情况。如果有人能指出我应该采取哪些步骤来提高处理这些数据的性能和速度,我将不胜感激。泰:)

更新:这是基于 Rick James 回答的实际查询:

UPDATE templates AS t
         JOIN equipos as e ON e.codigos  = t.npsegment1
         JOIN ubicaciones u ON u.attribute1  = t.atributo1
         JOIN tiendas ti ON ti.nombre_doc_stock = t.atributo1
         JOIN estados es on es.nporganizationid  = t.nporganizationid
         JOIN almacenes a on a.npsecondarycode  = t.npsecondarycode
         SET t.inclusion = e.inclusion,
             t.ubicacion = u.ubicacion11,
             t.tienda_id = ti.idi2b,
             t.estado = es.estado,
             t.considerar = a.considerar

Templates 表有 66K 条记录

【问题讨论】:

    标签: php mysql performance


    【解决方案1】:

    查找多表UPDATE。您可能能够在单个 SQL 语句中执行整个操作。它会运行得更快。类似的东西

    UPDATE table1
        JOIN table2 ON ...
        JOIN table3 ON ...
        ....
        SET table1.col1 = ...,
            table1.col2 = ...,
            ....;
    

    不要使用 MyISAM。

    更多

    查询是将多个表中的内容复制到一个表中 (t)?如果您是从头开始创建t,那么创建INSERT INTO t SELECT ... JOIN ... 可能会快得多

    如果您确实需要大量更新,并且如果列是独立的,那么一次执行一张表可能会更快。也就是说,

    UPDATE t JOIN e ON ... SET t.inclusion = e.inclusion;
    UPDATE t JOIN u ON ... SET t.... = u....;
    etc.
    

    我怀疑问题的一部分是锁定了这么多表中的这么多行。

    另一种方法是将任务“分块”。我讨论了here。总体上需要更长的时间,但每个块都会在文明的时间内完成。

    【讨论】:

    • 让我们看看“永无止境”查询的 SQL。
    • 刚刚用实际查询更新了我的问题..谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多