I'm trying to normalize a table in MySQL, converting a table with many similar columns to a many-to-many relationship with two columns. I have following tables:
person:
+----+------+
| id | name |
+----+------+
| 1 | John |
| 2 | Anna |
| 3 | Leon |
+----+------+
person_temp:
+------+--------+--------+--------+--------+
| name | color1 | color2 | color3 | color4 |
+------+--------+--------+--------+--------+
| John | red | blue | green | |
| Anna | green | yellow | | |
| Leon | blue | red | | |
+------+--------+--------+--------+--------+
color:
+----+--------+
| id | name |
+----+--------+
| 1 | red |
| 2 | blue |
| 3 | green |
| 4 | yellow |
+----+--------+
I would like to delete person_temp after populating the many-to-many relation table like this:
person-color:
+-----------+----------+
| person_id | color_id |
+-----------+----------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 3 |
| 2 | 4 |
| 3 | 2 |
| 3 | 1 |
+-----------+----------+
However, I haven't found any solution to my query. The only relationship I have to the id of the person is the name in person_temp. I know names are unique in person, so it wouldn’t be a problem to use them for the query.
I tried with this SQL, but it isn’t working because person_temp doesn't have an id column.
INSERT INTO `person_color`
SELECT p.id, c.id
FROM (
SELECT id, color1 color
FROM person_temp
UNION
SELECT id, color2 FROM person_temp
UNION
SELECT id, color3 FROM person_temp
UNION
SELECT id, color4 FROM person_temp
UNION
SELECT id, color5 FROM person_temp
) p
JOIN color c
ON c.name = p.color;