简体   繁体   中英

Count in Mysql table values

There is a column in table called "Freq", its meant to count search values, Each search is updated in new row on table, I'm looking for PHP code to count values for each row and update it back in Table. (could be a loop action?)

For example: value rr123456789il, is search 20 times. I want the Freq cell to show 20 on each row with same searched code,

在此处输入图片说明

update table

$sql_update = "UPDATE enterlog SET Email='$email', Freq='$frequency'  WHERE LogID='$last_id'";

I think that it will better if you create a new table freq when all frequencies will be there to avoid having redundant data.

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
);

Then you can rut the following query to initialize you table:

INSERT INTO freq (LogID, freq)
(SELECT LogID, 1
FROM enterlog
)
ON DUPLICATE KEY UPDATE freq = freq + 1;

Also, you have to run this query every time you make an insertion to your enterlog table so frequencies will be up to date.

Try something like this.

$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.'"';

Iterate over the Itemcodes and update their respective frequencies:

$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();

Just to show the principle. There are some optimization possibilities, like using a prepared statement for the query in the loop, but that I will leave up to you.

There also should be a way to do that with a subquery in a single SQL statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM