我的目标是将来自不同架构的表合并为一个单一的架构,因此我想执行此查询:
INSERT INTO inventory.maintenance
SELECT *
FROM (
SELECT NULL, 'A' as department_id, maintenance.* FROM a_inventory.maintenance
UNION
SELECT NULL, 'B' as department_id, maintenance.* FROM b_inventory.maintenance
UNION
SELECT NULL, 'E' as department_id, maintenance.* FROM e_inventory.maintenance
UNION
SELECT NULL, 'L' as department_id, maintenance.* FROM l_inventory.maintenance
UNION
SELECT NULL, 'M' as department_id, maintenance.* FROM m_inventory.maintenance
) AS tmp_maintenance
我必须对许多不同的表执行此查询,并且并非所有部门中的所有表都如此。与其手动编写每个查询,不如增加一些自动化...
SET @department = ('A', 'B', 'E', 'L', 'M');
SET @connection = 'inventory';
SET @table = 'maintenance';
/* MAGIC HERE to create @union */
SET @s = CONCAT(
'INSERT INTO ', @connection, '.', @table,
'SELECT * FROM (', @union, ') AS tmp');
PREPARE stm1 FROM @s; EXECUTE stm1; DEALLOCATE PREPARE stm1;
我想从@union
创建@department
。我曾尝试使用REPEAT
,但实际上并没有用。
答案 0 :(得分:0)
解决此问题的一种可能方法。但是您需要在某个地方有一个表departments
,并假设id
是id
时可以从中提取char
:
SET @department = 'A,B,E,L,M' COLLATE utf8mb4_unicode_ci;
SET @connection = 'inventory';
SET @table = 'maintenance';
SET @union = '';
SELECT @union := CONCAT(
@union,
' SELECT NULL, "', id , '", ',
@table,'.* FROM ', id, '_',
@connection, '.', @table,
' UNION '
)
FROM departments WHERE FIND_IN_SET(id, @department);
SELECT @union := SUBSTRING(@union, 1, LENGTH(@union) - LENGTH('UNION '));
SET @s = CONCAT(
'INSERT INTO ', @connection, '.', @table, ' '
'( SELECT * FROM (', @union, ') AS tmp)');
SELECT @s;
PREPARE stm1 FROM @s; EXECUTE stm1; DEALLOCATE PREPARE stm1;