简体   繁体   中英

mySQL query across multiple schemas

I have a multi-schema structure (same table across all schemas).

Here is how I can fetch all the schemas:

select table_schema from information_schema.tables where table_name = 'messages' and TABLE_TYPE = 'BASE TABLE'

This query is for a join between 'messages' table across two tables-

select *, '1' as customer from customer_1.messages union select *,  '2' as customer from customer_2.messages

How do I use the perform the above query for all the schemas from the first query? Need not be a join. Could be anything that helps me return the results across all schemas.

Note: There could be 5000-10000 schemas

DELIMITER @@;

CREATE PROCEDURE join_all_data()
BEGIN
    SET @counter := 0;
    SELECT GROUP_CONCAT('select *, ',
                        @counter := @counter + 1,
                        ' as customer from ',
                        table_schema,
                        '.messages'
                        SEPARATOR ' UNION ALL ')
        FROM information_schema.tables 
        WHERE table_name = 'messages' 
          AND table_type = 'BASE TABLE'
        INTO @sql;
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DROP PREPARE stmt;
END
@@;

DELIMITER ;

CALL join_all_data;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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