MySQL MySQL更新列+1?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3866524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 17:22:00  来源:igfitidea点击:

MySQL Update Column +1?

mysqlsqlsql-updateaggregate-functions

提问by Cory

I was wondering what would be the easiest way to update a column by +1? I will be updating a post count of a category based on when users submits a new post.

我想知道通过 +1 更新列的最简单方法是什么?我将根据用户提交新帖子的时间更新类别的帖子数。

Thanks.

谢谢。

回答by OMG Ponies

The easiest way is to notstore the count, relying on the COUNT aggregate function to reflect the value as it is in the database:

最简单的方法是存储计数,依靠 COUNT 聚合函数来反映数据库中的值:

   SELECT c.category_name,
          COUNT(p.post_id) AS num_posts
     FROM CATEGORY c
LEFT JOIN POSTS p ON p.category_id = c.category_id

You can create a viewto house the query mentioned above, so you can query the view just like you would a table...

您可以创建一个视图来容纳上面提到的查询,这样您就可以像查询表一样查询视图...

But if you're set on storing the number, use:

但是,如果您要存储号码,请使用:

UPDATE CATEGORY
   SET count = count + 1
 WHERE category_id = ?

..replacing "?" with the appropriate value.

..替换“?” 具有适当的值。

回答by Michael Banzon

You can do:

你可以做:

UPDATE categoriesSET posts= posts+ 1 WHERE category_id= 42;

UPDATE categoriesSET posts= posts+ 1 WHERE category_id= 42;

回答by Vincent Ramdhanie

How about:

怎么样:

update table
set columnname = columnname + 1
where id = <some id>

回答by KoolKabin

update post set count = count + 1 where id = 101

回答by praveenraj4ever

update TABLENAME
set COLUMNNAME = COLUMNNAME + 1
where id = 'YOURID'

回答by Ahamadullah Saikat

update table_name set field1 = field1 + 1;