我是 PHP-MySQL 的新手。我有两个 MySQL 表:
- 具体性:包含 8 万个单词的具体性分数的表格
- Brian:一个包含 100 万行的表,每行包含一个或两个单词。
我有一个小的 PHP 脚本,它获取“Brian”中的每一行,解析它,查找“Concreteness”中的分数并将其记录在“Brian”中。
我一直在与其他几个表一起运行此脚本,这些表有 300-400k 行,每行有数百个单词。 “Brian”则不同,因为它有 100 万行,每行 1 或 2 个单词。由于某种原因,我的脚本对于 Brian 来说非常慢。
这是实际的脚本:
<?php
include "functions.php";
set_time_limit(0); // NOTE: no time limit
if (!$conn)
die('Not connected : ' . mysql_error());
$remove = array('{J}','{/J}','{N}','{/N}','{V}','{/V}','{RB}','{/RB}'); // tags to remove
$db = 'LCM';
mysql_select_db($db);
$resultconcreteness = mysql_query('SELECT `word`, `score` FROM `concreteness`') or die(mysql_error());
$array = array(); // NOTE: init score cache
while($row = mysql_fetch_assoc($resultconcreteness))
$array[strtolower($row['word'])] = $row['score']; // NOTE: php array as hashmap
mysql_free_result($resultconcreteness);
$data = mysql_query('SELECT `key`, `tagged` FROM `brian`') or die(mysql_error()); // NOTE: single query instead of multiple
while ($row = mysql_fetch_assoc($data)) {
$key = $row['key'];
$tagged = $row['tagged'];
$weight = $count = 0;
$speech = explode(' ', $tagged);
foreach ($speech as $word) {
if (preg_match('/({V}|{J}|{N}|{RB})/', $word, $matches)) {
$weight += $array[strtolower(str_replace($remove, '', $word))]; // NOTE: quick access to word's score
if(empty($array[strtolower(str_replace($remove, '', $word))])){}else{$count++;}
}
}
mysql_query('UPDATE `brian` SET `weight`='.$weight.', `count`='.$count.' WHERE `key`='.$key, $conn) or die(mysql_error());
// Print out the contents of the entry
Print "<b>Key:</b> ".$info['key'] . " <br>";
}
mysql_free_result($data);
?>
最佳答案
我猜真正的问题是您向数据库发出的 100 万条 mysql 更新语句。考虑捆绑更新语句(并删除打印):
$i=0;
while ($row = mysql_fetch_assoc($data)) {
// ... left out the obvious part
$sql .= "'UPDATE `brian` SET `weight`='.$weight.', `count`='.$count.' WHERE `key`='.$key;";
$i++;
if ($i%1000 == 0) {
mysql_query($sql) or die(mysql_error());
$i=0;
$sql = "";
}
}
// remember to save the last few updates
mysql_query($sql) or die(mysql_error());
关于php - PHP - MySQL 脚本非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26319453/