MySQL将PHP cron job SQL结合到一个查询中是否可能?

时间:2016-02-11 12:26:49

标签: php mysql cron

我在php-cron作业上运行php-script。我想知道有可能我可以在一个MySQL查询中做同样的事情吗?

$sql = "SELECT COUNT(`user_to`) AS fav_count , user_to  FROM `users_favorite` WHERE 1 GROUP BY `user_to` ";
$result = mysql_query($sql, $db) or die("Error in query:" . mysql_error());
while ($row = mysql_fetch_array($result)) {
    $fav_count = $row['fav_count'];
    $user_id = $row['user_to'];
    $sql1 = "UPDATE user SET fav_count='" . $fav_count . "'
                    WHERE user_id=" . $user_id . " ";
    $result1 = mysql_query($sql1, $db) or die("Error in query:" . mysql_error());
}

1 个答案:

答案 0 :(得分:2)

您可以将updatejoin一起用于此:

UPDATE user u JOIN
       (SELECT COUNT(`user_to`) AS fav_count, user_to 
        FROM `users_favorite` 
        GROUP BY `user_to` 
       ) uf
       ON uf.user_to = u.user_id
    set u.fav_count = uf.fav_count;

如果您希望它保持最新,您可能需要考虑触发器来维护摘要表中的计数。然而,这将是对系统的这个组件的重新设计。