简体   繁体   English

创建一个表,其列名从另一个表的行值派生

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

Suppose I have the following table with a single column: 假设我有一个包含单列的下表:

Table_1 表格1

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

And I want to create a new table with the following column names: 我想创建一个包含以下列名的新表:

Table_2 TABLE_2

| pk | A | B | C |

That is, the data from one table become the column names of the second table. 也就是说,来自一个表的数据成为第二个表的列名。 There may be a pivot involved at some level, but I'm unable to really get the answer. 在某种程度上可能涉及到一个支点,但我无法真正得到答案。

I tried: 我试过了:

create table Table_2 (
  select group_concat(distinct(nameCol), " varchar(50), ")
  from Table_1
);

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 . 请看这里的小提琴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM