Consider a database with these three tables:
category:
cat_id name parent_id
-----------------------
1 drinks 0
2 carbonated 1
3 cola 2
4 water 1
5 rc-cola 3
product:
prod_id name default_cat
-----------------------------------
1 cola-zero 2
2 mineral water 4
cat_prod:
cat_id prod_id
---------------
1 1
2 1
3 1
4 2
We have category hierarchy and a product, which may belong to several categories.
Also, each product has a default category. In this case cola-zero
product has default category 2
- carbonated
, which is a mistake. Default category has to be 3
- cola
. I.e., the lowest category in the category tree. However, I may consider only a subset of the category tree: only those categories that the product belongs to.
I need to update the default category of each product in the product
table and ensure that product's default category is the most "defined" one, i.e., the lowest for a given product.
I can write a script, which would retrieve all categories, build the tree in memory and then for each product check the default category against this tree. But I hope there is a smarter way to do this via SQL only.
Is it even possible to do it in pure SQL?
Thanks.