创建具有从另一个表的行值派生的列名的表 [英] Create a table with column names derived from row values of another table
本文介绍了创建具有从另一个表的行值派生的列名的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我的下表只有一列:
Suppose I have the following table with a single column:
表_1
-----------
| nameCol |
-----------
| A |
| A |
| B |
| C |
-----------
我想用以下列名创建一个新表:
And I want to create a new table with the following column names:
表_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.
我尝试过:
create table Table_2 (
select group_concat(distinct(nameCol), " varchar(50), ")
from Table_1
);
推荐答案
您可以使用动态查询:
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;
请在此处看到小提琴.
这篇关于创建具有从另一个表的行值派生的列名的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文