我想将表A中的数据复制/更新到表B.表B还有一些额外的列。我尝试了以下选项。
1) `REPLACE INTO `B` (SHOW FIELDS FROM 'A') SELECT * FROM `A
2) `REPLACE INTO `B`
(SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='test1' AND `TABLE_NAME`='A') SELECT * FROM `A
但它会引发错误。你能帮助我如何用选择查询选择名字吗?
更新
3)正如Jerko所说,
我有两个表A(warehouse_id,long,lat)B(warehouse_id,long)
应用以下声明。
SET @query = CONCAT('REPLACE INTO `A` (SELECT ',
(SELECT GROUP_CONCAT(CONCAT('`',column_name, '`'))
FROM information_schema.columns
WHERE `TABLE_SCHEMA`='test2' AND `table_name` = 'A'),
' FROM `B`)');
PREPARE stmt FROM @query;
EXECUTE stmt;
这给了我错误
“#1054 - '字段列表'中的未知列'lat'”
答案 0 :(得分:3)
你不能像在尝试那样在mysql中动态地执行此操作。 MySQL期望直接提供列名列表,而不是从子查询中提供。
如果你想动态地这样做,你将不得不向上游退回到用于与MySQL交互的任何语言,例如PHP或Java。
答案 1 :(得分:2)
你试过这个吗?
insert into B(col1, . . ., coln)
select col1, . . ., coln
from A;
即,列出A
子句中select
的字段。列出B
列列表中insert
的相应列。
如果您需要列列表,请从INFORMATION_SCHEMA.COLUMNS
获取并剪切并粘贴到查询中。
答案 2 :(得分:1)
试试这个
INSERT INTO B (field1,field2,...,fieldN)
SELECT (field1,field2,...,fieldN) FROM A
答案 3 :(得分:1)
实际上有一种方法
SET @query = CONCAT('REPLACE INTO `A` (',
(SELECT GROUP_CONCAT(CONCAT('`',column_name, '`'))
FROM information_schema.columns
WHERE `TABLE_SCHEMA`='test1' AND `table_name` = 'A'
AND column_name IN (SELECT column_name FROM information_schema.columns WHERE table_schema = 'test1' AND table_name='B')) ,
') (SELECT ',
(SELECT GROUP_CONCAT(CONCAT('`',column_name, '`'))
FROM information_schema.columns
WHERE `TABLE_SCHEMA`='test1' AND `table_name` = 'A'
AND column_name IN (SELECT column_name FROM information_schema.columns WHERE table_schema = 'test1' AND table_name='B')),
' FROM `B`)');
PREPARE stmt FROM @query;
EXECUTE stmt;