查询并从所有数据库中获取所有数据库名称和子查询特定表

时间:2018-04-14 09:57:44

标签: subquery concat multiple-databases

我有不同的数据库。我在每个数据库中都有表。 我想知道我是否可以询问有多少数据库,例如' schema' ' MySQL的'我曾经知道如何执行第一个问题产生的所有数据库的特定表所询问的子查询。

example.
the structure would be
db1 -> user-> id,name,imei,telephone,etc..
db2 -> user-> id,nameuser,imei,telephone,etc..
db3 -> user-> id,nameuser,imei,telephone,etc..
....
db1000 -> user-> id,nameuser,imei,telephone,etc..

the query are how this, but this get error

    SELECT CONCAT('SELECT * FROM ' schema_name 'where imei.'schema_name =     nameimai)
    FROM information_schema.schemata
    WHERE schema_name NOT IN ('information_schema','mysql','performance_schema','sys','performance_schema','phpmyadmin');

    Results

    name db    id          name       imei        phone
    ---------- ---------- ---------- ---------- ----------
    db1         1            John     76876876  xxx
    db2         2300         John     76876876   xxxx  
    ...
    db1000       45          John     76876876   xxx

在一个查询中可能

感谢..

1 个答案:

答案 0 :(得分:0)

以下是使用存储过程执行此操作的一种方法。

如果我理解正确,您有多个具有相同表(用户)的数据库,并且您希望针对特定值对所有这些表运行查询。

我已经使这个相当通用,所以你可以传入表名和where子句。您的示例似乎是在寻找imei =' 76876876'的用户记录,因此如果我们使用该示例。

USE test;

DELIMITER //
DROP PROCEDURE IF EXISTS multidb_select //
-- escape any quotes in the query string
-- call multidb_select ('usertest','WHERE imei = \'76876876\'')
CREATE PROCEDURE multidb_select(IN tname VARCHAR(64), IN qwhere VARCHAR(1024))
  READS SQL DATA
BEGIN
  DECLARE vtable_schema VARCHAR(64);
  DECLARE vtable_name VARCHAR(64);

  DECLARE done BOOLEAN DEFAULT FALSE;
  -- exclude views and system tables
  DECLARE cur1 CURSOR FOR 
    SELECT `table_schema`, `table_name`
    FROM `information_schema`.`tables`
    WHERE `table_name` = tname
    AND `table_type` = 'BASE TABLE'
    AND `table_schema` NOT IN 
      ('information_schema','mysql','performance_schema',
       'sys','performance_schema','phpmyadmin')
    ORDER BY `table_schema` ASC;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done := TRUE;

  OPEN cur1;
  SET @unionall := '';

  read_loop: LOOP
    FETCH cur1 INTO vtable_schema, vtable_name;
    IF done THEN
      LEAVE read_loop;
    END IF;

    -- UNION ALL in case the id is the same  
    IF CHAR_LENGTH(@unionall) = 0 THEN
      SET @unionall = 
        CONCAT("SELECT \'", vtable_schema , "\' AS 'Db', t.* FROM `", 
                vtable_schema, "`.`" , vtable_name, "` t ", qwhere);
    ELSE
      SET @unionall = 
        CONCAT(@unionall, " UNION ALL SELECT \'", vtable_schema , 
                "\' AS 'Db', t.* FROM `", vtable_schema, 
                "`.`", vtable_name, "` t ", qwhere);
    END IF;  

  END LOOP;
  CLOSE cur1;

  PREPARE stmt FROM @unionall;
  EXECUTE stmt;   
  DEALLOCATE PREPARE stmt;

END //

DELIMITER ;

使用

运行它
call test.multidb_select('user','WHERE imei = \'76876876\'')