I am looking to add a new column to table using the suggestions provided here and here
In essence, I would like the (fields_in_orig_table) to be populated automatically, and not having to enter them manually (have many columns and this changes from table to table):
CREATE TABLE games_new LIKE games_orig;
ALTER TABLE games_new ADD COLUMN location varchar(256);
INSERT INTO games_new (fields_in_orig_table) SELECT * FROM games_orig;
RENAME TABLE games_orig TO games_old, games_new TO games_orig;
DROP TABLE games_old;
My thought goes around this:
CREATE TABLE games_new LIKE games_orig;
ALTER TABLE games_new ADD COLUMN version varchar(256);
INSERT INTO games_new
(SELECT CONCAT(GROUP_CONCAT(column_name ORDER BY ordinal_position
SEPARATOR " , "), " ") AS columns
FROM information_schema.columns
WHERE table_schema = 'games' AND table_name = 'games_orig' )
SELECT * FROM games_orig;
RENAME TABLE games_orig TO games_old, games_new TO games_orig;
DROP TABLE games_old;
This gives me syntax error (near the Select concat....).
The original syntax to get comma delimited column listings is:
SELECT CONCAT("'", GROUP_CONCAT(column_name ORDER BY ordinal_position SEPARATOR "', '"), "'") AS columns
FROM information_schema.columns
WHERE table_schema = 'db_name' AND table_name = 'tbl_name'
In my query, I have removed the extra quotes, as I figure my query does not require quotes as part of the column listing.
What am I doing wrong here? Who could help, please?
INSERT INTO games_new
VALUES (SELECT CONCAT....
When inserting values in the table use INSERT INTO tablename VALUES (fields)
instead of INSERT INTO tablename SET(fields)
.
CREATE TABLE games_new LIKE games_orig;
ALTER TABLE games_new ADD COLUMN version varchar(256);
INSERT INTO games_new
VALUES
(SELECT CONCAT(GROUP_CONCAT(column_name ORDER BY ordinal_position
SEPARATOR ' , '), ' ') AS columns
FROM information_schema.columns
WHERE table_schema = 'games' AND table_name = 'games_orig' )
SELECT * FROM games_orig;
RENAME TABLE games_orig TO games_old, games_new TO games_orig;
DROP TABLE games_old;
You haven't specified which column you want to insert into, because your nested query is returning only 1 value
INSERT INTO games_new (column_name_u_want_to_insert_value_into)
SELECT cast(concat(group_concat(column_name ORDER BY ordinal_position SEPARATOR " , "), " ") AS CHAR) AS columns
FROM information_schema.columns
WHERE table_name = 'games_orig';
also, if you are running all the statements together, add semicolon(;) for the insert query as well
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.