Full example.
1) Create tables and data (code)
CREATE TABLE Product_categories (product_reference VARCHAR(8), category_id INT, subcategories VARCHAR(8));
INSERT INTO Product_categories VALUES
('REF.001',1,'1/2'),
('REF.002',2,'1/2/3/4');
CREATE TABLE Categories (id INT, name VARCHAR(32));
INSERT INTO Categories VALUES
(1,'example_category_1'),
(2,'example_category_2'),
(3,'example_category_3'),
(4,'example_category_4');
CREATE TABLE Importer (product_reference VARCHAR(8), category VARCHAR(128));
INSERT INTO Importer (product_reference) VALUES
('REF.001'),
('REF.002');
2) Check data (console output)
mysql> SELECT * FROM Product_categories;
+-------------------+-------------+---------------+
| product_reference | category_id | subcategories |
+-------------------+-------------+---------------+
| REF.001 | 1 | 1/2 |
| REF.002 | 2 | 1/2/3/4 |
+-------------------+-------------+---------------+
2 rows in set (0.00 sec)
mysql> SELECT * FROM Categories;
+------+--------------------+
| id | name |
+------+--------------------+
| 1 | example_category_1 |
| 2 | example_category_2 |
| 3 | example_category_3 |
| 4 | example_category_4 |
+------+--------------------+
4 rows in set (0.00 sec)
mysql> SELECT * FROM Importer;
+-------------------+----------+
| product_reference | category |
+-------------------+----------+
| REF.001 | NULL |
| REF.002 | NULL |
+-------------------+----------+
2 rows in set (0.00 sec)
3) Perform update (code)
UPDATE Importer i, (SELECT pc.product_reference,GROUP_CONCAT(c.name ORDER BY n.n SEPARATOR '>') category
FROM (SELECT 1 n UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) n
JOIN Product_categories pc
JOIN Categories c ON SUBSTRING_INDEX(SUBSTRING_INDEX(CONCAT('',pc.subcategories,'////'),'/',n.n),'/',-1) = c.id
GROUP BY pc.product_reference
) d
SET i.category = d.category
WHERE i.product_reference = d.product_reference;
4) Check result (console output)
mysql> SELECT * FROM Importer;
+-------------------+-----------------------------------------------------------------------------+
| product_reference | category |
+-------------------+-----------------------------------------------------------------------------+
| REF.001 | example_category_1>example_category_2 |
| REF.002 | example_category_1>example_category_2>example_category_3>example_category_4 |
+-------------------+-----------------------------------------------------------------------------+
2 rows in set (0.00 sec)
1/2
? And the value you want to finish with isexample_category_1>example_category_2
? If that is the case, then it's tricky. Can you change your schema to have two records in Product_categories, differing only by the values in the subcategories attribute - i.e.1
for one record and2
for the other?subcategories
is1/2
. And yes, the value i want to finish with isexample_category_1>example_category_2
Product_categories.subcategories
can contain>
symbol? DoesCategories.name
can contain/
symbol?