我有以下表格:data_1
,data_1
,data_3
,data_4
,(数据_ *)。
所有相同字段的名称。
我想将这些表中的所有错误条目(where error != ''
)插入到data_error
表中,但仅限于特定字段。
如何归档?
答案 0 :(得分:1)
如果您想按照表名的某个规则浏览所有表:
CREATE DEFINER=`root`@`localhost` PROCEDURE `TEST_TABLE_LOOP` ()
BEGIN
DECLARE data_TableName VARCHAR(50) DEFAULT '';
DECLARE is_Done INT DEFAULT FALSE;
DECLARE insert_MainCursor CURSOR FOR SELECT table_name FROM information_schema.tables WHERE table_name LIKE '<FILTER GOES HERE>';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET is_Done = TRUE;
OPEN insert_MainCursor;
read_loop:LOOP
FETCH insert_MainCursor INTO data_TableName;
IF is_Done THEN
LEAVE read_loop;
END IF;
SET @sql = CONCAT('INSERT INTO <DESTINATION_TABLE_NAME_HERE> SELECT <COLUMN1>, <COLUMN2> FROM ', data_TableName, ' WHERE <SOMETHING_SOMETHING_GOES_HERE>');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP read_loop;
CLOSE insert_MainCursor;
END
答案 1 :(得分:0)
我想你想做点什么:
insert into table (fields)
select field from data_1
where error <> 1;
如果您想在包含所有表的单个查询中执行此操作,则可以执行某些操作
insert into table (fields)
select field from data_1
where error <> 1
UNION
select field from data_2
where error <> 1
UNION
select field from data_3
where error <> 1;
依旧......
答案 2 :(得分:0)
INSERT INTO data_error (column1, column2, column3)
SELECT column1, column2, column3
FROM data_1
WHERE error != ''
UNION ALL
SELECT column1, column2, column3
FROM data_2
WHERE error != ''
UNION ALL
SELECT column1, column2, column3
FROM data_3
WHERE error != ''
UNION ALL
SELECT column1, column2, column3
FROM data_4
WHERE error != ''