如何从两个db获取数据并使用SQL插入临时表?

时间:2016-05-09 10:27:47

标签: mysql

我有两个数据库oldnew。我想从两个数据库中计算记录并插入带有表名的新临时表。

我创建了临时表:

CREATE TEMPORARY TABLE tempemp (tablename varchar(50),northwindcount int(11),dest_northwindcount int(11));

并计算记录:

select (select count(*) from northwind.orders) as northwind_cnt, (select count(*) from dest_northwind.orders) as dest_northwind_cnt;

如何插入临时表?

2 个答案:

答案 0 :(得分:1)

关于MySql的Dunno,但是在MS SqlServer T-SQL中,你会做这样的事情:

INSERT INTO
    Tempemp(
       tablename,northwindcount,dest_northwindcount)
SELECT 
    '???' AS table make,
        (SELECT COUNT(*) FROM Northwind.Orders)
       AS Northwindcount,
    (SELECT COUNT(*) FROM Dest_Northwind.Orders) 
        AS dest_northwindcount

我的语法可能有些偏差,但一般的想法是INSERT语句可以有一个SELECT子句而不是VALUES子句。也许在MySql中有类似的东西?

答案 1 :(得分:0)

我为此编写程序,现在这是有效的。 谢谢大家。

BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE newcount INTEGER;
DECLARE oldcount INTEGER;
DECLARE oldtableName char(50);
DECLARE newtableName char(50);

DECLARE curs1 CURSOR FOR SELECT TABLE_NAME,SUM(TABLE_ROWS) as count FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dest_northwind' AND 
TABLE_NAME IN(select table_name from information_schema.tables
where table_schema='dest_northwind') GROUP BY TABLE_NAME ;

DECLARE curs2 CURSOR FOR SELECT TABLE_NAME,SUM(TABLE_ROWS) as count FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'northwind' AND 
TABLE_NAME IN(select table_name from information_schema.tables
where table_schema='northwind') GROUP BY TABLE_NAME ;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN curs1;
OPEN curs2;
read_loop: LOOP
FETCH curs1 INTO newtableName,newcount;
FETCH curs2 INTO oldtableName,oldcount;
IF done THEN
LEAVE read_loop;
END IF;
SELECT newtableName,newcount,oldcount;
insert into zreult1(Tablename,Northwind,Dest_Northwind)values(oldtableName,oldcount,newcount);
END LOOP;
CLOSE curs1;
CLOSE curs2;
END