古い MySQL PHP メソッド呼び出しを更新しようとしていますが、同じ結果を得るために同じ SELECT 呼び出しを 2 回呼び出すことになります。これを行うより良い方法はありますか?
ここにオリジナルがあります:
function updateProbabilities()
{
// first update the word count of each category
$rs = $this->con->select("SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id");
$total_words = 0;
while (!$rs->EOF()) {
$total_words += $rs->f('total');
$rs->moveNext();
}
$rs->moveStart();
if ($total_words == 0) {
$this->con->execute("UPDATE nb_categories SET word_count=0, probability=0 WHERE 1");
return true;
}
while (!$rs->EOF()) {
$proba = $rs->f('total')/$total_words;
$this->con->execute("UPDATE nb_categories SET word_count=".(int)$rs->f('total').",
probability=".$proba."
WHERE category_id = '".$rs->f('category_id')."'");
$rs->moveNext();
}
return true;
}
これが私のバージョンです:
function updateProbabilities() {
$sql = "SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id";
$res = mysql_query($sql) or die (mysql_error());
$total_words = 0;
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
$total_words += $row['total'];
}
if ($total_words >= 1) {
$sql = "SELECT category_id, SUM(count) AS total FROM nb_wordfreqs WHERE 1 GROUP BY category_id";
$res = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
$proba = $row['total']/$total_words;
$count = (int)$row['total'];
$sql = "UPDATE nb_categories SET word_count=".$count.",
probability=".$proba."
WHERE category_id = '".$row['category_id']."'";
mysql_query($sql) or die (mysql_error());
}
}
else {
$sql = "UPDATE nb_categories SET word_count=0, probability=0 WHERE 1";
mysql_query($sql) or die (mysql_error());
}
return true;
}
この 2 回目の重複した SELECT 呼び出しを回避する方法はありますか?