计入 Mysql table 个值
Count in Mysql table values
在 table 中有一列叫做 "Freq",它的意思是计算搜索值,
每个搜索都会在 table 的新行中更新,
我正在寻找 PHP 代码来计算每行的值并在 Table 中更新它。 (可能是循环动作?)
例如:值rr123456789il,被搜索了20次。我希望 Freq 单元格每行显示 20 个相同的搜索代码,
更新table
$sql_update = "UPDATE enterlog SET Email='$email', Freq='$frequency' WHERE LogID='$last_id'";
尝试这样的事情。
$freq = (int)$row['Freq']; // $row being the result row for $last_id.
$sql_update = 'UPDATE `enterlog` SET
`Email` = "'.$email.'",
`Freq` = "'.($freq + 1).'"
WHERE `LogID` = "'.$last_id.'"';
迭代项目代码并更新它们各自的频率:
$db = new mysqli("localhost", "my_user", "my_password", "world");
// fetch itemcodes and their frequencies
$sql = 'SELECT Itemcode, COUNT(*) AS count FROM enterlog GROUP BY Itemcode';
$qq = $db->query($sql);
while (list($itemcode, $count) = $qq->fetch_row()) {
// update all rows having the itemcode with the appropriate frequence
$sql = 'UPDATE enterlog SET freq='.$count.' WHERE Itemcode="'.$itemcode.'"';
$db->query($sql);
}
$qq->free_result();
只是为了说明原理。有一些优化的可能性,比如在循环中为查询使用准备好的语句,但我会留给你。
还应该有一种方法可以在单个 SQL 语句中使用子查询来做到这一点。
我认为如果您创建一个新的 table 频率会更好,因为所有频率都将在那里以避免出现冗余数据。
CREATE TABLE freq (
LogID int unsigned not null,
freq int unsigned DEFAULT 0,
foreign key(LogID) references enterlog(LogID) ON DELETE CASCADE ON UPDATE CASCADE
);
然后你可以通过以下查询来初始化你 table:
INSERT INTO freq (LogID, freq)
(SELECT LogID, 1
FROM enterlog
)
ON DUPLICATE KEY UPDATE freq = freq + 1;
此外,每次插入 enterlog
table 时,您都必须 运行 此查询,以便频率是最新的。
在 table 中有一列叫做 "Freq",它的意思是计算搜索值, 每个搜索都会在 table 的新行中更新, 我正在寻找 PHP 代码来计算每行的值并在 Table 中更新它。 (可能是循环动作?)
例如:值rr123456789il,被搜索了20次。我希望 Freq 单元格每行显示 20 个相同的搜索代码,
更新table
$sql_update = "UPDATE enterlog SET Email='$email', Freq='$frequency' WHERE LogID='$last_id'";
尝试这样的事情。
$freq = (int)$row['Freq']; // $row being the result row for $last_id.
$sql_update = 'UPDATE `enterlog` SET
`Email` = "'.$email.'",
`Freq` = "'.($freq + 1).'"
WHERE `LogID` = "'.$last_id.'"';
迭代项目代码并更新它们各自的频率:
$db = new mysqli("localhost", "my_user", "my_password", "world");
// fetch itemcodes and their frequencies
$sql = 'SELECT Itemcode, COUNT(*) AS count FROM enterlog GROUP BY Itemcode';
$qq = $db->query($sql);
while (list($itemcode, $count) = $qq->fetch_row()) {
// update all rows having the itemcode with the appropriate frequence
$sql = 'UPDATE enterlog SET freq='.$count.' WHERE Itemcode="'.$itemcode.'"';
$db->query($sql);
}
$qq->free_result();
只是为了说明原理。有一些优化的可能性,比如在循环中为查询使用准备好的语句,但我会留给你。
还应该有一种方法可以在单个 SQL 语句中使用子查询来做到这一点。
我认为如果您创建一个新的 table 频率会更好,因为所有频率都将在那里以避免出现冗余数据。
CREATE TABLE freq (
LogID int unsigned not null,
freq int unsigned DEFAULT 0,
foreign key(LogID) references enterlog(LogID) ON DELETE CASCADE ON UPDATE CASCADE
);
然后你可以通过以下查询来初始化你 table:
INSERT INTO freq (LogID, freq)
(SELECT LogID, 1
FROM enterlog
)
ON DUPLICATE KEY UPDATE freq = freq + 1;
此外,每次插入 enterlog
table 时,您都必须 运行 此查询,以便频率是最新的。