Mysql: creating columns from select statement

I was wondering if it is possible to create columns based on the result from the Select statement.

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

So, if I chose Select availableColumns From Table1, how can I create a table that has the following structure, the results should be used to create the columns:

 column1 | column2 | column3 

If I try:

 CREATE TABLE test SELECT availableColumns FROM table1 

I get the following:

 Column ------ Column1 Column2 Column3 

Therefore, instead of columns, I get the result in the form of rows that I do not need.

Thank you in advance:)

+4
source share
1 answer

You can have a list of columns for a particular table by selecting them from the Information Schema table

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

To create a table, just use it

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

Just change the 'databasename' and 'tablename' to match the actual database and table

+3
source

Source: https://habr.com/ru/post/1484222/


All Articles