Create a table with column names derived from row values of another table

后端 未结 1 485
南方客
南方客 2021-01-05 08:05

Suppose I have the following table with a single column:

Table_1

-----------
| nameCol |
-----------
| A       |
| A       |
| B       |
| C       |         


        
1条回答
  •  被撕碎了的回忆
    2021-01-05 08:43

    You could use a dynamic query:

    SELECT
      CONCAT(
        'CREATE TABLE Table_2 (',
        GROUP_CONCAT(DISTINCT
          CONCAT(nameCol, ' VARCHAR(50)')
          SEPARATOR ','),
        ');')
    FROM
      Table_1
    INTO @sql;
    
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    

    Please see fiddle here.

    0 讨论(0)
提交回复
热议问题