MySQL查询所有具有相同表和列名称的数据库

时间:2013-10-09 23:15:41

标签: mysql database dynamic tablename

假设我们有以下2个数据库:

    DROP DATABASE IF EXISTS `adb`;
    CREATE DATABASE `adb` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
    USE `adb`;

    CREATE TABLE IF NOT EXISTS `Login` (
       `ID` bigint(20) NOT NULL,
       `Login` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
       PRIMARY KEY (`ID`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

    INSERT INTO `Login` (`ID`, `Login`) VALUES
     (1, '2012-11-09 11:18:29'),
     (2, '2012-12-22 21:48:48'),
     (3, '2013-01-01 12:39:22');



    DROP DATABASE IF EXISTS `bdat`;
    CREATE DATABASE `bdat` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
    USE `bdat`;

   CREATE TABLE IF NOT EXISTS `Login` (
     `ID` bigint(20) NOT NULL,
     `Login` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`ID`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

   INSERT INTO `Login` (`ID`, `Login`) VALUES
   (1, '2011-11-09 15:15:15'),
   (2, '2012-12-22 13:08:18'),
   (3, '2010-02-11 17:00:02');

我们还有2个查询。

Query1是:

       SELECT table_schema AS "Database", round(sum(data_length+index_length)/1024/1024,4) AS "Size (MB)" FROM information_schema.tables GROUP BY table_schema;

Query2是:

       SELECT Max(Login) AS "Last Login" FROM Login

如何将两个查询组合在一起以获得以下结果?

     Database             Size (MB)   Last Login
     adb                   0.0020     2012-12-22 13:08:18
     bdat                  0.0020     2013-01-01 12:39:22
     information_schema    0.0078     NULL
     mysql                 0.6133     NULL

1 个答案:

答案 0 :(得分:0)

如果使用大于5.0的Mysql版本,可以使用 FEDERATED TABLES.

例如,在 BDAT 中,使用以下代码创建 FEDERATED TABLE ADB

CREATE TABLE federated_Login (
       `ID` bigint(20) NOT NULL,
       `Login` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
       PRIMARY KEY (`ID`)
)
ENGINE=FEDERATED
DEFAULT CHARSET=latin1
CONNECTION='mysql://root@remote_host:9306/federated/Login';

然后您可以使用 federated_Login 作为 BDAT 的本地表格,以获取更多信息:

http://dev.mysql.com/doc/refman/5.0/es/federated-use.html