i have an really old database with a really bad table structure and I'm trying to create these tables with a better structure. For doing this, I need to match two tables, to get the id of a category.
Here are my two old tables:
table categorys:
| ID | catname | cat1 | cat2 | cat3 | cat4 |
+----+--------------+--------+-------------+---------+------+
| 1 | bike | bike | NULL | NULL | NULL |
| 2 | accessories | bike | accessories | NULL | NULL |
| 3 | helmets | bike | accessories | helmets | NULL |
| 4 | lights | bike | accessories | lights | NULL |
| 5 | led | bike | accessories | lights | led |
table products:
| ID | productnr | productname | cat1 | cat2 | cat3 | cat4 |
+----+-------------+---------------+-------+-------------+---------+------+
| 1 | 451157 | productya | bike | accessories | NULL | NULL |
| 2 | 555523 | product11 | bike | accessories | helmets | NULL |
| 3 | 234432 | helmetxqa | bike | accessories | helmets | NULL |
| 4 | 666623 | lightblue | bike | accessories | lights | NULL |
| 5 | 542123 | foobarlight | bike | accessories | lights | led |
At first I would like to get rid of the columns cat1, 2, 3 and 4 from the products table.
So that I get a result like this:
| ID | catId | productnr | productname |
+----+---------+------------+---------------+
| 1 | 2 | 451157 | productya |
| 2 | 3 | 555523 | product11 |
| 3 | 3 | 234432 | helmetxqa |
| 4 | 4 | 666623 | lightblue |
| 5 | 5 | 542123 | foobarlight |
Could some one tell me, how I should make a query which checks if all 4 cat's are matching, and then give's me the cat'id? I've tried it this way, but I think it's the wrong way, because everytime a product only has 2 or 3 cat's I don't get the associated catId. So it only works for products with all 4 cat's defined.
SELECT
cat.`id`,
prod.`productnr`,
prod.`productname`
FROM
products as prod
LEFT JOIN
categorys as cat
ON
cat.`cat1` = prod.`cat1`
AND
cat.`cat2` = prod.`cat2`
AND
cat.`cat3` = prod.`cat3`
AND
cat.`cat4` = prod.`cat4`
If someone has also useful tipps for me, please tell me about. ;-)
Thanks for helping me out :)