I need to update a hierarchical structure in MySql. It's about categories in a shop.
Table:
CREATE TABLE `categories` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`sort` int(11) NOT NULL,
`level` int(11) NOT NULL,
`visible` tinyint(1) NOT NULL DEFAULT '1',
`product_count` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `sort` (`sort`),
KEY `visible` (`visible`)
);
+------+------------------------------+---------------+-------+------+
| id | name | product_count | level | sort |
+------+------------------------------+---------------+-------+------+
| 1 | Cat1 | 0 | 0 | 0 |
| 2 | Cat1.1 | 0 | 1 | 1 |
| 3 | Cat1.1.1 | 82 | 2 | 2 |
| 4 | Cat2 | 4 | 0 | 3 |
| 5 | Cat3 | 0 | 0 | 4 |
| 6 | Cat3.1 | 0 | 1 | 5 |
| 7 | Cat3.2 | 0 | 1 | 6 |
| 8 | Cat3.2.1 | 12 | 2 | 7 |
| 9 | Cat3.2.1.1 | 0 | 3 | 8 |
The hierarchical structure is create with the fields "sort" and "level". I couldn't change this because it's not "my" table-design.
I need an UPDATE which set the field "visible" to true or false according to the rule: "A categorie is visible if it contains products OR if it is a parent of a categorie that contains products".
So in my example the result should be:
+------+------------------------------+---------+
| id | name | visible |
+------+------------------------------+---------+
| 1 | Cat1 | 1 |
| 2 | Cat1.1 | 1 |
| 3 | Cat1.1.1 | 1 |
| 4 | Cat2 | 1 |
| 5 | Cat3 | 1 |
| 6 | Cat3.1 | 0 |
| 7 | Cat3.2 | 1 |
| 8 | Cat3.2.1 | 1 |
| 9 | Cat3.2.1.1 | 0 |
Is it possible to solve this with one query in MySql 5.6?