Skip to content
Advertisement

SQL UPDATE base on COUNT

I have two tables

  • product-table with fields (id, category_id)
  • category-table with fields (id, num_of_products)

The product table contains multiple products in different categories. And I know how to count product in each categories using

But how do I update category.num_of_product using a single sql query with the result of the SELECT …. ? I have tried but can not figure out the proper syntax !!

Any suggestions ?

Advertisement

Answer

Try this query:

If you want to do UPDATE with JOIN, you must do the JOIN first then followed with SET. If there are conditions then you need to add WHERE after the SET. For example, let’s say there are some category you don’t want to update then probably:

Demo fiddle

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement