Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mysql

Suppose I have the following table with a single column:

Table_1

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

And I want to create a new table with the following column names:

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
);
like image 885
Alptigin Jalayr Avatar asked Apr 04 '13 19:04

Alptigin Jalayr


People also ask

How can you create a new table with existing data from another table?

A copy of an existing table can be created using a combination of the CREATE TABLE statement and the SELECT statement. The new table has the same column definitions. All columns or specific columns can be selected.

How do I create a column from another table in SQL?

Question: How can I create a SQL table from another table without copying any values from the old table? Answer: To do this, the SQL CREATE TABLE syntax is: CREATE TABLE new_table AS (SELECT * FROM old_table WHERE 1=2);

How do you reference data from another table in SQL?

In SQL, to fetch data from multiple tables, the join operator is used. The join operator adds or removes rows in the virtual table that is used by SQL server to process data before the other steps of the query consume the data.


1 Answers

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.

like image 188
fthiella Avatar answered Sep 16 '22 11:09

fthiella