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
);
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.
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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With