MySQL insert normalized data in multiple rows in wp_postmeta

I am trying to insert multiple rows into wp_postmeta. I can’t figure out the correct SQL query to attain it.
The problem I am facing is that my current data looks like this:

Col 1  | Col 2  | Col 3  | Col 4  | Col5
----------------------------------------
A      | B      | C      | D      | E
F      | G      | H      | I      | J

And I need to insert it into wp_postmeta like this:

Read More
Col 1  | Col 2  | Col 3  
-----------------------
A      | txt    | B
A      | txt    | C
A      | txt    | D
A      | txt    | E
F      | txt    | G
F      | txt    | H
F      | txt    | I
F      | txt    | J

The “txt” data is not a problem, I am just trying to figure out a way to “denormalize” each row in my source data and store it in four different rows in the other table.

Related posts

Leave a Reply

1 comment

  1. You can unpivot the data using a UNION ALL query which takes the data from the columns and converts it into rows:

    select `col 1`, `col 2` as val
    from yourtable
    union all
    select `col 1`, `col 3` as val
    from yourtable
    union all
    select `col 1`, `col 4` as val
    from yourtable
    union all
    select `col 1`, `col5` as val
    from yourtable
    order by 1
    

    See SQL Fiddle with Demo.

    Once you have the data into this format, then you can INSERT it into another table.