我需要将数据从一个表复制到另一个表。表没有所有相同的列或顺序;但是要复制的数据总是在同一列中;应将列foo
中的数据复制到foo
列。
如果 只有两个表,我可以对列名进行硬编码,如:
INSERT INTO table_target ( column1, column2, column4 )
SELECT column1, column2, column4 FROM table_source;
然而,有几十个表,并且需要进行一些额外的转换,所以如果我可以说:复制任何匹配的列并忽略其余的,那就太好了。
我已经设法弄清楚如何获取常见列的列表,但现在我被卡住了。
SELECT src.col
FROM (SELECT COLUMN_NAME as col
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'table_target') as trg
INNER JOIN
(SELECT COLUMN_NAME as col
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'table_source') as src ON (src.col=trg.col)
;
答案 0 :(得分:2)
SELECT CONCAT(
'INSERT INTO table_target (',
GROUP_CONCAT(trg.col), -- produces output like "col1, col2, col3"
') SELECT ',
GROUP_CONCAT(trg.col), -- produces output like "col1, col2, col3"
' FROM table_source;') as sql_stmt
FROM (
(SELECT COLUMN_NAME as col
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'table_target') as trg
INNER JOIN
(SELECT COLUMN_NAME as col
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'table_source') as src ON src.col=trg.col) x;
这使用了mysql方便的GROUP_CONCAT
函数,该函数将值聚合到CSV中 - 非常适合创建用于生成SQL的列名列表
我还将您的查询包装在一个别名中,以便我们可以从中进行选择。