0

I have empty table below:

----------------
|id|c_id|c1|c2|c3|c4|
----------------
|  |    |  |  |  |  |

And another table:

|id|c_id|type|value|
--------------------
 1 |  1 | c1 | 234 |
-------------------
 2 |  1 | c2 | 211 |
-------------------
 3 |  3 | c2 |  4  |
--------------------
 5 |  4 | c3 |  54 |
--------------------
 5 |  5 | c4 | 789 |
--------------------
 6 |  2 | c1 | 234 |

I want to fill table1 with value from table2. As you can see column "type" will be devided into 4 columns in table 1. How I can do it with 1 query?

What i expect:

   |id|c_id| c1  | c2  |  c3  |  c4  |
    ----------------------------------
   |1 | 1  | 234 | 211 | null | null |
    ----------------------------------
   |2 | 2  | 234 | null| null | null | 
    ----------------------------------
   |3 | 3  | null|  4  | null | null |
    ----------------------------------
   |4 | 4  | null| null|  54  | null |
    ----------------------------------
   |5 | 5  | null| null| null | 789  |
Шыназ Алиш
  • 401
  • 2
  • 7
  • 23

1 Answers1

1

This is an ordinary pivot table operation:

INSERT INTO table1 (c_id, c1, c2, c3, c4)
SELECT c_id, MAX(CASE WHEN type = 'c1' THEN `value` END) AS c1,
             MAX(CASE WHEN type = 'c2' THEN `value` END) AS c2,
             MAX(CASE WHEN type = 'c3' THEN `value` END) AS c3,
             MAX(CASE WHEN type = 'c4' THEN `value` END) AS c4
FROM table2
GROUP BY c_id

DEMO

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612