简体   繁体   English

Mysql:从select语句创建列

[英]Mysql: create columns from select statement

I was wondering if you could create columns based on the result from a Select statement. 我想知道你是否可以根据Select语句的结果创建列。

Table 1:

availableColumns
-----------------
column1 -> record 1
column2 -> record 2
column3 -> record 3

So if I did a Select availableColumns From Table1, how could I create a table that has then the following structure, the results must be used to create columns: 因此,如果我从Table1执行Select availableColumns,我怎么能创建一个具有以下结构的表,结果必须用于创建列:

column1 | column2 | column3

If I try: 如果我尝试:

CREATE TABLE test SELECT availableColumns FROM table1

I get the following: 我得到以下内容:

Column
------
Column1
Column2
Column3

So instead of columns, I get my result as rows which I don't want. 因此,我将结果作为我不想要的行而不是列。

Thanks in advance :) 提前致谢 :)

You can have a list of columns for a specific table by selecting them from Information Schema table 通过从“ Information Schema表中选择特定表,可以获得列的列表

SELECT `COLUMN_NAME` 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='databasename' 
AND `TABLE_NAME`='tablename';

To create the table just use it 要创建表,只需使用它

CREATE TABLE test  SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='databasename' AND `TABLE_NAME`='tablename'; 

Just change 'databasename' and 'tablename' to fit your actual database and table 只需更改'databasename''tablename'以适合您的实际数据库和表

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

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