ALTER TABLE ADD COLUMN和自动COLUMNS列表

时间:2015-02-10 06:52:05

标签: mysql alter-table

我希望使用提供的建议herehere

向表中添加新列

本质上,我希望自动填充(fields_in_orig_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;

我的想法是:

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;

这给了我语法错误(在Select concat ....附近)。

获取逗号分隔列列表的原始语法是:

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'

在我的查询中,我删除了额外的引号,因为我认为我的查询不需要引号作为列列表的一部分。

我在这里做错了什么?谁能提供帮助呢?

3 个答案:

答案 0 :(得分:0)

INSERT INTO  games_new 

VALUES (SELECT CONCAT....

答案 1 :(得分:0)

在表格中插入值时,请使用INSERT INTO tablename VALUES (fields)代替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;

答案 2 :(得分:0)

您尚未指定要插入的列,因为嵌套查询仅返回1个值

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';

另外,如果你一起运行所有语句,也要为插入查询添加分号(;)