简体   繁体   English

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

[英]How to fetch data from two db and insert into temp table, using SQL?

I have two databases old and new .我有两个数据库oldnew I want to count record from both the databases and insert into new temporary table with their table name.我想从两个数据库中计算记录并用它们的表名插入到新的临时表中。

I created temporary table:我创建了临时表:

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

and counted records:并统计记录:

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

How can I insert into temp table?如何插入临时表?

Dunno about MySql, but in MS SqlServer T-SQL, you'd do something like this:不知道 MySql,但在 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

My syntax might be a little off, but the general idea is that an INSERT statement can have a SELECT clause instead of a VALUES clause.我的语法可能有点偏离,但总体思路是 INSERT 语句可以有一个 SELECT 子句而不是一个 VALUES 子句。 Maybe something similar in MySql?也许在 MySql 中有类似的东西?

i write procedure for this and now this is working.我为此编写了程序,现在正在运行。 thank you all.谢谢你们。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM