2011-12-23 87 views
-1

我有以下表格:data_1,data_1,data_3,data_4,(data_ *)。從多個表插入?

所有人都有相同的字段名稱。

我想將這些表中的所有錯誤條目(where error != '')插入到data_error表中,但只有特定的字段。

如何歸檔?

+0

聽起來像是你應該已經歸數據庫架構。什麼意思是「......但只有特定的領域」? – Matten 2011-12-23 16:41:14

回答

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; 

等。 。

+0

可以'data_1'爲通配符嗎?例如:'data_ *' – 2011-12-23 16:43:45

+0

不是直接。儘管如此,您可以通過存儲過程來完成此操作。這將是相同的想法,但是你首先得到所有具有該名稱的表,然後循環遍歷這些表。 – 2011-12-23 16:45:06

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 != '' 

MySQL Ref

+0

謝謝,是'data_ *'(通配符)不可能? – 2011-12-23 16:45:32

+0

使用通配符是不可能的。 – xbrady 2011-12-23 16:51:19

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