Search text in fields in every table of a MySQL database

前端 未结 24 1567
梦谈多话
梦谈多话 2020-11-22 06:23

I want to search in all fields from all tables of a MySQL database a given string, possibly using syntax as:

SELECT * FROM * WHERE * LIKE \'%stuff%\'
         


        
24条回答
  •  清酒与你
    2020-11-22 06:55

    Even if the following proposal should not be considered as a final solution you can achieve the goal by doing something like this:

    SET SESSION group_concat_max_len = 1000000;
    SET @search = 'Text_To_Search';
    
    DROP table IF EXISTS table1;
    CREATE TEMPORARY TABLE table1 AS 
    (SELECT 
        CONCAT('SELECT \'',TABLE_NAME,'\' as \'table_name\',\'',COLUMN_NAME,'\' as \'column_name\',CONVERT(count(*),char) as \'matches\' FROM `',
        TABLE_NAME,'` where `',COLUMN_NAME,'` like \'%',@search,'%\' UNION ') as 'query'
    FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'db_name' limit 1000000);
    
    set @query = (SELECT GROUP_CONCAT(t1.`query` SEPARATOR '') as 'final_query' from table1 t1 limit 1);
    set @query = (SELECT SUBSTRING(@query, 1, length(@query) - 7));
    
    PREPARE stmt FROM @query;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    

    Please remember that:

    1. Options: group_concat_max_len and limit 1000000 not always are needed, it will depends of your server/IDE configuration. Just in case I added them.

    2. After executing this you will get a 3 column response: [table_name], [column_name], [matches]

    3. Column 'matches' is the number of occurrences in the given table/column.

    4. This query is very fast.

    DISCLAIMER: It would be useful only for personal use, in other words please don't use it in a production system, because it is sensitive to SQL Injection attacks given that the search parameter is concatenated with other strings. If you want to create a prod. ready function, then you will need to create a store procedure with a LOOP.

提交回复
热议问题