[英]Count in Mysql table values
我认为,当所有频率都在那儿时创建一个新的表频率会更好,以避免有多余的数据。
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
);
然后,您可以通过以下查询来初始化表:
INSERT INTO freq (LogID, freq)
(SELECT LogID, 1
FROM enterlog
)
ON DUPLICATE KEY UPDATE freq = freq + 1;
另外,每次插入enterlog
表时都必须运行此查询,以便频率是最新的。
尝试这样的事情。
$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语句中使用子查询来执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.