php – 大规模MySQL更新最佳方法?
发布时间:2020-12-13 22:05:26 所属栏目:PHP教程 来源:网络整理
导读:我需要每天从CSV文件中更新 MySQL数据库中的库存水平3次. CSV中有超过27,000种产品需要更新,您可以想象它需要一段时间. 我目前有一个运行以下内容的PHP脚本: select * from products where product_code = "xxxxxxx";if num_rows 0 if new_stock_level = 0
我需要每天从CSV文件中更新
MySQL数据库中的库存水平3次.
CSV中有超过27,000种产品需要更新,您可以想象它需要一段时间. 我目前有一个运行以下内容的PHP脚本: select * from products where product_code = "xxxxxxx"; if num_rows > 0 if new_stock_level = 0 UPDATE products SET `stock` = 0,`price` = 9.99 where product_code = "xxxxxxx"; else UPDATE products SET `stock` = 50,`price` = 9.99,`stock_date` = now() where product_code = "xxxxxxx"; 如果你要更新<这一切都很好. 50件但不是27,000件! 更新此规模的最佳方法是什么? 我一直在做一些研究,从我所看到的mysqli准备好的陈述似乎是我应该去的地方. 在尝试了下面提到的一些内容以及我在线阅读的内容之后,我已经获得了一批250次更新的结果. 从InnoDB更改为MyISAM平均每秒的ubdate数量从7增加到27,这是一个巨大的增长. 案例准备9-10秒 ## Prepare the statment. $stmt = $mysqli->prepare("UPDATE products SET stock = case ? when 0 then 0 else ? end,price = ?,stock_date = case ? when 0 then stock_date else now() end WHERE product_code = ?"); $stmt->bind_param('dddds',$stock,$price,$prod); $stmt->execute(); 未准备好的声明9-10秒 $sql = "UPDATE products SET stock = case " . $stock . " when 0 then 0 else " . $stock . " end,price = " . $price . ",stock_date = case " . $stock . " when 0 then stock_date else now() end WHERE product_code = "" . $prod . "";n"; $mysqli->query($sql); 将命令分组为50并用multi_query 9-10秒进行激励 $mysqli->multi_query($sql); 如果我更新股票日期,则不准备2个单独的查询. 8-9秒 if($stock > 0) { $sql = "UPDATE products SET stock = " . $stock . ",stock_date = now() WHERE product_code = "" . $prod . "";n"; } else { $sql = "UPDATE products SET stock = " . $stock . ",price = " . $price . " WHERE product_code = "" . $prod . "";n"; } $mysqli->query($sql); 准备版本相同8-9秒 ## Prepare statments $stmt1 = $mysqli->prepare("UPDATE products SET stock = ?,stock_date = now() WHERE product_code = ?;"); $stmt1->bind_param('dds',$prod); $stmt2 = $mysqli->prepare("UPDATE products SET stock = ?,price = ? WHERE product_code = ?;"); $stmt2->bind_param('dds',$prod); if($stock > 0) { $stmt1->execute(); } else { $stmt2->execute(); } 我还尝试在VPS上添加一个额外的处理器,它使得它的速度提高了大约4个查询. 解决方法
关于这一点……
1. you can do this with one sql statement UPDATE products SET stock = case new_stock_level when 0 then 0 else new_stock_level end,price = 9.99,stock_date = case new_stock_level when 0 then stock_date else now() end WHERE product_code = "xxxxxxx"; 2. you might want to try wrapping the statements inside of a transaction: e.g. START TRANSACTION UPDATE products ...; UPDATE products ...; ... ; COMMIT TRANSACTION 这两件事应该加快速度. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |