TransWikia.com

How to get data from tables selected by reference from information_schema with some criteria in table name

Database Administrators Asked by Rajnikant Sharma on October 28, 2021

I am trying to get data like count or distinct from tables matching criteria in information_schema

SELECT 
    count(A.searchstring) 
FROM
    (SELECT 
        table_name 
     FROM 
        information_schema.tables 
     WHERE 
        table_name LIKE 'wozsearch_200716_%') A;

There are 100’s tables which have same structure but with different tables names, and I want to get the distinct values and row count of those tables.

A.searchstring is a column name in each table matching with table_name on the condition LIKE 'wozsearch_200716_%'.

From multiple table I can query total rows using:

SELECT sum(TABLE_ROWS)
FROM INFORMATION_SCHEMA.tables 
WHERE table_name LIKE 'wozsearch_200716_%'

But I want to find out:

SELECT distinct searchstring FROM  table_name LIKE 'wozsearch_200716_%'

Error I receive:

Error Code: 1054. Unknown column 'A.searchstring' in 'field list'

I have also tried using stored procedure

CREATE PROCEDURE `getdistinctrEs`(pattern char(50))
BEGIN
 DECLARE vtable_name TEXT;
        DECLARE getTempRecords CURSOR FOR SELECT a.`table_name` FROM INFORMATION_SCHEMA.tables a WHERE a.`table_name` LIKE pattern;
    open getTempRecords;
    c1:LOOP 
    FETCH getTempRecords INTO vtable_name;
  
    set @query=concat("SELECT distinct searchstring FROM ",vtable_name);
    prepare st from @query;
   execute st;
    END LOOP c1;
       
    close getTempRecords;
END

getting result in individual hundred of tabs and mysql stucks and i have to restart workbench

Please help me to solve my issue.

2 Answers

Write a stored procedure to build the SQL and insert the table name into that string. Then "execute" it.

Answered by Rick James on October 28, 2021

The stored procedure will produce for every table a separate result set.

You could INSERT The result of the SELECT into a temporary table, so that you have only one table as result:

DELIMITER // 
CREATE PROCEDURE `getdistinctrEs`(IN pattern varchar(50), IN searchstring varchar(50))
BEGIN
 DECLARE vtable_name TEXT;
        DECLARE getTempRecords CURSOR FOR SELECT a.`table_name` FROM INFORMATION_SCHEMA.tables a WHERE a.`table_name` LIKE pattern;
    open getTempRecords;
    c1:LOOP 
        FETCH getTempRecords INTO vtable_name;
  
        SET @query=concat("SELECT distinct ",searchstring," FROM ",vtable_name);
        PREPARE st from @query;
        EXECUTE st;
        DEALLOCATE PREPARE st;
    END LOOP c1;
       
    close getTempRecords;
END//
DELIMITER ;

Answered by nbk on October 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP