views:

32

answers:

4

Hello,

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.

Thanks.

+2  A: 

You can do:

UPDATE categories SET posts = posts + 1 WHERE category_id = 42;

mbanzon
+1 for good answer to the literal question
Amadan
A: 

How about:

update table
set columnname = columnname + 1
where id = <some id>
Vincent Ramdhanie
A: 
update post set count = count + 1 where id = 101
KoolKabin
+3  A: 

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

   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 view to 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.

OMG Ponies
+1 for a good answer to the problem, if not the question
Amadan
Thanks. Initially my thought to determine the amount of posts in a category would be to check the post tables for a cat_id matching that category and then add them up. Thought this may be resource consuming or less efficient than writing directly to that table.
Cory
It's very quick when you have an index on `p.post_id`.
Amadan