Search text in fields in every table of a MySQL database

前端 未结 24 1916
梦谈多话
梦谈多话 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:46

    This solution
    a) is only MySQL, no other language needed, and
    b) returns SQL results, ready for processing!

    #Search multiple database tables and/or columns
    #Version 0.1 - JK 2014-01
    #USAGE: 1. set the search term @search, 2. set the scope by adapting the WHERE clause of the `information_schema`.`columns` query
    #NOTE: This is a usage example and might be advanced by setting the scope through a variable, putting it all in a function, and so on...
    
    #define the search term here (using rules for the LIKE command, e.g % as a wildcard)
    SET @search = '%needle%';
    
    #settings
    SET SESSION group_concat_max_len := @@max_allowed_packet;
    
    #ini variable
    SET @sql = NULL;
    
    #query for prepared statement
    SELECT
        GROUP_CONCAT("SELECT '",`TABLE_NAME`,"' AS `table`, '",`COLUMN_NAME`,"' AS `column`, `",`COLUMN_NAME`,"` AS `value` FROM `",TABLE_NAME,"` WHERE `",COLUMN_NAME,"` LIKE '",@search,"'" SEPARATOR "\nUNION\n") AS col
    INTO @sql
    FROM `information_schema`.`columns`
    WHERE TABLE_NAME IN
    (
        SELECT TABLE_NAME FROM `information_schema`.`columns`
        WHERE
            TABLE_SCHEMA IN ("my_database")
            && TABLE_NAME IN ("my_table1", "my_table2") || TABLE_NAME LIKE "my_prefix_%"
    );
    
    #prepare and execute the statement
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    

提交回复
热议问题