I have a table persons
in a MySQL 5.6 database like this:
persons
---------------------------------------------------
| id | name | sports |
---------------------------------------------------
| 1 | Adam | Football,Hockey |
| 2 | Ben | Hockey,Tennis |
| 3 | Charlie | Basketball |
| 4 | Dennis | Hockey,Baseball |
---------------------------------------------------
As you can see, the column sports
is a string, but contains a list. The reason sports
is a string list is because the table was created from an automation step I cannot influence.
I want to find all Persons who like a certain sports type. Searching through the sports string column with %LIKE%
is of course inefficient.
I want to leave the table as it is but for the purpose of searching for persons who like a certain sports type with efficiency, I want to fill a new M:N table persons_sports
like this:
persons_sports
---------------------------------------------------
| id | person_id | sports |
---------------------------------------------------
| 1 | 1 | Football |
| 2 | 1 | Hockey |
| 3 | 2 | Hockey |
| 4 | 2 | Tennis |
| 5 | 3 | Basketball |
| 6 | 4 | Hockey |
| 7 | 4 | Baseball |
---------------------------------------------------
Of course I can write a script getting all rows from persons
, parsing the sports
column and then fill the new table but I wonder if there is a nice and elegant way to do this via a SQL statement on the database server directly?