如何使用SELECT COUNT()进行更新,但仅在存在count时避免将所有行设置为0

时间:2017-12-06 14:16:47

标签: mysql sql

所以我试图提出这个问题,这个问题已经复制了,基本上浪费了我的时间,因为它与复制问题无关。

How to get rid of the php wrapping on this sql query

我到目前为止,我可以影响具有新视图的行。然而,遗憾的是,所有其他人都将归结为0。

UPDATE `posts` SET `views_count` = views_count + (SELECT COUNT(*) AS `views` FROM `posts__views` WHERE `post_id` = `posts`.`id` GROUP BY `post_id`);

所以我想,我需要一些WHERE,在第一个UPDATE中避免影响行,有0个视图。

在UPDATE调用之后,posts__views表被截断。否则上述方法就可以了。

编辑:我的目标是更新帖子views_count,对 posts__views 表中的单个视图进行统计和分组。在主SQL过程之后, posts__views 会被截断,并且会生成新视图。

最初代码是用PHP编写的:

<?  
# find new views grouped together:
$find_views = db::query("SELECT `post_id`, COUNT(*) AS `post_views` FROM `posts__views` WHERE `date_imported` IS NULL GROUP BY `post_id`;");
while ($view = db::fetch($find_views)) {

    # Update the main production tables views_count column:
    db::query("UPDATE `posts` SET `views_count` = views_count + {$view['post_views']} WHERE `id` = '{$view['post_id']}';");

    # Update the post's views table... but why does it actually needs this update hmm..
    db::query("UPDATE `posts__views` SET `date_imported` = NOW() WHERE `date_imported` IS NULL AND `post_id` = '{$view['post_id']}';");
}

# Trunkate post's views:
db::query("TRUNCATE TABLE `posts__views`;");

0 个答案:

没有答案